KotaBear233 KotaBear233 - 5 months ago 12x
Swift Question

NSData baseEncodedString returning nil

What am I doing wrong in my swift project? My line

NSData.init(base64EncodedString: parameters[0], options: .IgnoreUnknownCharacters)

is returning nil.

parameters[0] = "LFGNzD83/G8"


Doesn't look like that's a valid b64 string. Try this web app to encode some text https://www.base64decode.org/. For example, VGVzdGluZw== is the word testing.

let b64String = "VGVzdGluZw==" // Is "Testing" b64 encoded from utf8
let encodedData = NSData.init(base64EncodedString: b64String, options: [])
print(String(data: encodedData!, encoding: NSUTF8StringEncoding)) // > "Testing"

Noted in another SO answer, "padding at the end which is 0, 1 or 2 '=' characters" It is possible to know if a string is encoded in base64?

So it looks like a quick check of equal signs at the end is enough to tell you it's not base64.