Jacob Platin Jacob Platin - 1 year ago 87
iOS Question

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

I am currently converting a user-picked

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
, but I can't convert that into a
. Any thoughts? I have already tried using both PNG and JPEG methods for the
, 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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download