finneycanhelp
finneycanhelp

Reputation: 9248

New Swift Way For Base64EncodedStringFromData Objective-C

I am converting Objective-C to Swift and ran into code that is turning an Apple App Store receipt NSData into a base64 encoded string.

The code is using the function Base64EncodedStringFromData from https://github.com/stackmob/stackmob-ios-sdk/blob/master/Utility/Base64EncodedStringFromData.m

From a stackoverflow post titled Base64 Encoding/Decoding with Swift 2, I see how to encode NSData.

let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

However, I think I should do the following instead if I want the result to be the same as the Base64EncodedStringFromData function:

let base64String = transactionReceipt.base64EncodedStringWithOptions([])

Are the "Base64EncodedStringFromData" and transactionReceipt.base64EncodedStringWithOptions([]) equivalent? I plan on experimenting. However, I want to make sure the concept is correct.

Upvotes: 2

Views: 314

Answers (1)

dirtydanee
dirtydanee

Reputation: 6151

Are these two equivalent? - The answer is no, but it depends on the length of your string.

If you take a look on the Apple documentation, it clearly states, if you not specify a line length, than the encoding will be Carriage Return + Line Feed.

Also, i have written a small test to take a look, because i am also using base64 encoding.

 let someShortString = "someShortString"
 let encodedShortString = someShortString.dataUsingEncoding(NSUTF8StringEncoding)!


 let someLongString = "someLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongStringsomeLongString"
 let encodedLongString = someLongString.dataUsingEncoding(NSUTF8StringEncoding)!

 let base64ShortStringWithoutParameters = encodedShortString.base64EncodedStringWithOptions([])
 let base64ShortStringWithParameters = encodedShortString.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)


 let base64LongStringWithoutParameters = encodedLongString.base64EncodedStringWithOptions([])
 let base64LongStringWithParameters = encodedLongString.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

 base64ShortStringWithoutParameters == base64ShortStringWithParameters ? print("same") : print("not same")
 base64LongStringWithoutParameters == base64LongStringWithParameters ? print("same") : print("not same")

It will print "same" for the first statement and "not same" for the second one.

So in conclusion, if your string is longer than a certain length(what might be 64 characters, but i am not sure), they will not be the same. There will be "\r\n" inserted into the converted string.

Upvotes: 1

Related Questions