Swift NSData from base64encoded string returns nil

For others that may be having this issue, make sure your Base64 encoded string has a length divisible by 4 (= should be used to pad the length).

See this StackOverflow answer here: https://stackoverflow.com/a/36366421/330494


Try to use IgnoreUnknownCharacters option.

Or try to use initWithBase64EncodedString from NSDataAdditions


This can also happen if the input is so-called "URL Safe" Base64 data. This data has the + symbol replaced by the - symbol, and the / symbol replaced by the _ symbol.

Fortunately it's straightforward to convert it:

inputString = [[inputString stringByReplacingOccurrencesOfString:@"-" withString:@"+"] stringByReplacingOccurrencesOfString:@"_" withString:@"/"];

A full list of variants is available on Wikipedia.