decodedData is nil but My base64String contains an extremely long string
var imgProfile:NSData = UIImagePNGRepresentation(imgUI)
let base64String = imgProfile.base64EncodedStringWithOptions(.allZeros)
let base64String = prefs.valueForKey("imgDefault") as? String
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0) )
var decodedimage = UIImage(data: decodedData!)
There are two different problems:
It would appear that the
+ characters have been replaced with spaces. That will happen if you submit an
application/x-www-form-urlencoded request without percent escaping the
+ characters. This probably happened when you first sent the base64 string to be stored in the database.
See http://stackoverflow.com/a/24888789/1271826 for a discussion of some percent encoding patterns. The key point here is to not rely upon
stringByAddingPercentEscapesUsingEncoding, because that will allow
+ characters to go unescaped.
The string is also missing the trailing
= characters. (The string's length should be a multiple of four, and in this case, it's two characters short, so there should be
== at the end of the rendition with the
+ characters in it (the "before" string). While that is sometimes a mistake made by poorly designed base64-encoders, this is not a problem that
base64EncodedStringWithOptions suffers from.
In this case, it looks like a much longer base64 string must have been truncated somehow. (Your strings are suspiciously close to 1024 characters. lol.) This truncation could happen if you put the parameters in the URL rather than the body of the request. But nothing in this code sample would account for this behavior, so the problem rests elsewhere.
But look at the
length of the original
NSData. The base64 string should be 1/3 larger than that (plus rounded up to the nearest four characters, once you include the trailing
And, once you decode the string that you've provided and look at the actual contents, you can also see that the base64 string was truncated. (According to the portion provided, there should be 1484 bytes of
IDAT data, and there's not, plus there's no
IEND chunk ... don't worry about those details, but rest assured that it's basically saying that the PNG data stream is incomplete.)