Reputation: 1
I have created an app in which the user selects a profile photo. It is saved in the documents directory as NSData. I am having trouble finding code that will allow me to now retrieve it and show it in the UI Image View. Any help would be appreciated.
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerController.SourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true) {
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
profileImageView.image = image
let imageData: NSData = image.pngData()! as NSData
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsPath = paths[0] //Get the docs directory
let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent("userprofilephoto.png").absoluteString //Add the file name
imageData.write(toFile: filePath, atomically: true) //Write the file
self.dismiss(animated: true, completion: nil)
} else {
//error message
}
}
override func viewDidLoad() {
super.viewDidLoad()
profileImageView.layer.cornerRadius = profileImageView.bounds.size.height / 2.0
}
Upvotes: 0
Views: 50
Reputation: 2571
You can fetch the saved image like this:
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("userprofilephoto.png")
let retrieved_img = UIImage(contentsOfFile: imageURL.path)
// retrieved_img is your UIImage
}
Upvotes: 1