2017-04-14 42 views
0

我在我的程序中使用了UIImagePickerController,它有效地改變了我添加的imageview的圖像。但是,每當我重新啓動此應用程序並返回到主屏幕時,它都會自動重置爲之前的默認圖像,而不是用戶選擇的圖像。我怎樣才能讓它記錄上次使用的圖像,並在每次程序啓動時重新加載它?在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) 
} 
+0

我承擔你的意思是一個真正的應用程序重新啓動(即它的內存不足),而不是僅僅點擊主屏幕,然後重新啓動應用程序? – toddg

+3

您需要將圖像保存到某個地方並在下次啓動應用程序時加載它 –

+0

@LeoDabus我該怎麼做?請引導我。 – Ajp

回答

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以前保存的avatarImage並從那裏加載它:

// 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) 
    } 
} 
相關問題