NSData to UIImage

Try this code. This worked for me.

Saving the data.

create path to save the image.

let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
                                                               .userDomainMask,
                                                               true)[0]
let libraryURL = URL(fileURLWithPath: libraryDirectory, isDirectory: true)
let fileURL = libraryURL.appendingPathComponent("image.data")

convert the image to a Data object and save it to the file.

let data = UIImageJPEGRepresentation(myImage, 1.0)
try? data?.write(to: fileURL)

retrieving the saved image

let newImage = UIImage(contentsOfFile: fileURL.relativePath)

Create an imageview and load it with the retrieved image.

let imageView = UIImageView(image: newImage)
self.view.addSubview(imageView)

Leave a Comment