将ImageView内容保存在内存中?什么是最好的方法?

时间:2016-07-09 15:20:07

标签: ios xcode swift

我整个上午都在网上寻找这个答案,而且我找不到我需要的答案。我希望用户从他的库中添加一个图像,它将出现在屏幕上。我设法编写了允许我这样做的代码。但是,我希望保存该图像。通过这种方式,我的意思是我希望在用户关闭应用程序并重新打开它之后仍然会显示所选图像。我怎样才能做到这一点? 任何帮助将非常感激 :) 我附上了我的代码:

import UIKit

class Schedule: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet var imageView: UIImageView!   
let imagePicker = UIImagePickerController()    
@IBAction func addImage(sender: AnyObject) {

    imagePicker.allowsEditing = false
    // Only allow photos to be picked, not taken.
    imagePicker.sourceType = .PhotoLibrary        
    presentViewController(imagePicker, animated: true, completion: nil)        
}


// User picks image

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage                
    }        
    dismissViewControllerAnimated(true, completion: nil)                
}

// User cancels picking image action

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()        
    imagePicker.delegate = self        
}    
}

1 个答案:

答案 0 :(得分:1)

您可以使用NSUserDefault执行此操作,它会存储您的图像数据,您可以稍后检索它。像这样更改viewDidLoad

override func viewDidLoad() {
super.viewDidLoad()        
     imagePicker.delegate = self 
     if let imageData = NSUserDefaults.standardUserDefaults().objectForKey("image") as? NSData {
         self.imageView.image = UIImage(data: imageData)
     }
}  

现在,当您从NSUserDefault

中选择图片时,您需要将此imageData存储在UIImagePicker
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
         imageView.contentMode = .ScaleAspectFit
         imageView.image = pickedImage
         let data = UIImagePNGRepresentation(pickedImage)              
         NSUserDefaults.standardUserDefaults().setObject(data, forKey: "image")
         NSUserDefaults.standardUserDefaults().synchronize() 
     }        
     dismissViewControllerAnimated(true, completion: nil)                
}

希望这会对你有所帮助。