我创建了一个应用,用户可以在其中选择个人资料照片。它作为NSData保存在文档目录中。我在查找代码时遇到了麻烦,该代码现在允许我检索它并将其显示在UI图像视图中。任何帮助将不胜感激。
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
}
答案 0 :(得分:1)
您可以这样获取保存的图像:
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
}