Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift encoding/decoding images for JSON

I'm kinda new to swift and i need some help with encoding some image, putting it in a JSON and after retrieving it, decoding it back to NSData and recreating the image in an UIImage view controller. I've found this post Convert Image to Base64 string in iOS + Swift but i get stuck with this part:

let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)

because the fromRaw method is not available anymore.

Thanks in advance

Later edit: I'm using swiftyJson to parse the array and i'm getting the image data like this:

var base64String = arrayJson[0]["photo"].stringValue
var imageString = base64String as NSString

and after that i'm trying to decode it like this:

let decodedData = NSData(base64EncodedString: imageString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

I've also tried with the rawValue instead of IgnoreUnknownCharacters. Both return nil. Also tried with the base64String instead of imageString. Same thing.

like image 745
Adrian Stoicescu Avatar asked Mar 02 '15 18:03

Adrian Stoicescu


1 Answers

You can do the following instead to make a base64 encoded string to an UIImage:

 //base64 string to NSData
 let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))

//NSData to UIImage
var decodedIamge = UIImage(data: decodedData!)

NSDataBase64EncodingOptions.fromRaw(0)! now is changed to NSDataBase64DecodingOptions(rawValue: 0)

For more encode/decode details, you can visit this post: Convert between UIImage and Base64 string

like image 171
ztan Avatar answered Oct 30 '22 01:10

ztan