Jacob Platin Jacob Platin - 4 months ago 52
iOS Question

Base64 conversion with UIImage: NSData is not nil, but NSImage is nil

I am currently converting a user-picked UIImage to a base64 string using the below method, but when I go to convert that back into an image using the below method, I can get the NSData, but I can't convert that into a UIImage. Any thoughts? I have already tried using both PNG and JPEG methods for the UIImage, and neither worked if that adds any detail.



Encoding Code:

var base64 = UIImagePNGRepresentation(self.profileView.image!))!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

Decoding Code:

let decodedData = NSData(base64EncodedString: String(user?.photoURL), options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedimage = UIImage(data: decodedData!) //this decoded image is nil


You can try with code:

let image : UIImage = UIImage(named:"your_image")!
let imageData:NSData = UIImagePNGRepresentation(image)!


let base64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)


let dataDecoded:NSData = NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

Here is the code to convert NSData to UIImage

let image: UIImage = UIImage(data:dataDecoded,scale:1.0)

I hope this helps.