Swift 中的 UIImagePickerController 图像
Posted
技术标签:
【中文标题】Swift 中的 UIImagePickerController 图像【英文标题】:UIImagePickerController image in Swift 【发布时间】:2017-04-14 19:11:56 【问题描述】:我在我的程序中使用 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)
【问题讨论】:
我假设您的意思是实际的应用重启(即内存不足),而不是仅仅点击主屏幕然后重新启动应用? 您需要将图像保存在某处,并在您的应用下次启动时加载它 @LeoDabus 我该怎么做?请指导我。 另存为 jpeg ***.com/questions/29726643/… 你需要有某种持久层。你可以使用数据库、Core Data 甚至 NSUserDefaults。稍后我会尝试整理一个示例。 【参考方案1】:由于应用程序内存不足,您需要某种持久性机制来保存图像。最简单的方法是将图像存储在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)
【讨论】:
以上是关于Swift 中的 UIImagePickerController 图像的主要内容,如果未能解决你的问题,请参考以下文章