简体   繁体   English

将数据从字符串编码为 NSData Swift 中的 HTTBody 字节

[英]Encode data from String to bytes for HTTBody in NSData Swift

I'm developing a gateway link to a bank in which to enter the credit card number, make a payment to prove that the credit card is correct.我正在开发一个到银行的网关链接,在其中输入信用卡号,付款以证明信用卡是正确的。 Android I have no problem but in iOS with Swift I don't get it to work. Android 我没有问题,但在 iOS 中使用 Swift 我无法正常工作。 Currently I have a String that is the thing I have to send the URL, the problem is that this PostData Bytes must be in base64, but failed to convert it.目前我有一个字符串,它是我必须发送 URL 的东西,问题是这个 PostData 字节必须在 base64 中,但无法转换它。

This is what I have in Android:这是我在 Android 中所拥有的:

EncodingUtils.getBytes(mstrPostData, "base64")

This take the String and convert to Bytes in base64 encoding.这需要字符串并以 base64 编码转换为字节。

I need the same with Swift and after converted, put inside a NSData to assign in HTTBody from my Request Object我需要与 Swift 相同,并在转换后放入 NSData 以从我的请求对象中分配 HTTBody

EDIT: I solved the problem with these:编辑:我解决了这些问题:

let utf8str: NSData = postString.dataUsingEncoding(NSUTF8StringEncoding)!

let base64Encoded: String = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

let data: NSData = NSData(base64EncodedString: base64Encoded as String, options: NSDataBase64DecodingOptions(rawValue: 0))!

Another error I found is a parameter that I put inside postString is SHA1 and one of the values was incorrect.我发现的另一个错误是我放在 postString 中的一个参数是 SHA1,其中一个值不正确。

For iOS7+, you can use the built-in method of NSData:对于iOS7+,可以使用NSData的内置方法:

NSString *string = [data base64EncodedStringWithOptions:kNilOptions];

if mstrPostData is an NSString, you can convert to NSData:如果 mstrPostData 是 NSString,则可以转换为 NSData:

NSData* data = [mstrPostData dataUsingEncoding:NSUTF8StringEncoding];

this is Objective-C code这是 Objective-C 代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM