Swift 中的 UIImagePickerController 图片

UIImagePickerController image in Swift

我在我的程序中使用了 UIImagePickerController,它有效地改变了我添加的图像视图的图像。但是,每当我重新启动此应用程序并返回主屏幕时,它会自动重置为我之前使用的默认图像,而不是用户选择的图像。我怎样才能让它记录上次使用的图像,并在每次程序启动时重新加载它?

 var imagePicker = UIImagePickerController()
 func chooseImage(_ sender: Any) { //function called with button press

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    imagePickerController.allowsEditing = true

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in

        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }else{
            print("Camera not available")
        }


    }))

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in
        self.avatarImageView.image = UIImage(named: "Avatar.png")


    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(actionSheet, animated: true, completion: nil)


}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerEditedImage] as! UIImage

    avatarImageView.image = image

    picker.dismiss(animated: true, completion: nil)



}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

由于应用程序内存不足,您需要某种持久性机制来保存图像。最简单的方法是将图像存储在 UserDefaults 中。这可以这样完成:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let image = info[UIImagePickerControllerEditedImage] as! UIImage
    avatarImageView.image = image
    UserDefaults.standard.set(UIImagePNGRepresentation(image), forKey: "avatarImage")    

    picker.dismiss(animated: true, completion: nil)
}

然后当您重新打开应用程序时,您需要检查您之前是否在 UserDefaults 中保存了头像图像并从那里加载它:

// Could be in viewDidLoad or wherever else you load your image
override func viewDidLoad() {

    if let imageData = UserDefaults.standard.object(forKey: "avatarImage") as? Data {
        avatarImageView.image = UIImage(data: imageData)
    }
}