简体   繁体   中英

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. 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.

This is what I have in Android:

EncodingUtils.getBytes(mstrPostData, "base64")

This take the String and convert to Bytes in base64 encoding.

I need the same with Swift and after converted, put inside a NSData to assign in HTTBody from my Request Object

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.

For iOS7+, you can use the built-in method of NSData:

NSString *string = [data base64EncodedStringWithOptions:kNilOptions];

if mstrPostData is an NSString, you can convert to NSData:

NSData* data = [mstrPostData dataUsingEncoding:NSUTF8StringEncoding];

this is Objective-C code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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