2016-07-09 62 views
0

我一直在網上尋找這個答案整個上午,我沒有找到我所需要的。我希望用戶從他的庫中添加一個圖像,它會出現在屏幕上。我設法編寫了允許我這樣做的代碼。但是,我想要保存該圖像。由此,我的意思是我希望所選圖像在用戶關閉應用程序並重新打開後仍然出現。我怎樣才能做到這一點? 任何幫助將非常感激:) 我們已經附上我的代碼:將ImageView內容保存在內存中?什麼是最好的方法?

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

爲此,可以使用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) 
    } 
} 

現在你需要這個的imageData存儲NSUserDefault當你從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)     
} 

希望這將幫助您選擇圖像。

+0

我想我明白你寫的是什麼。我將這些添加到我的代碼中。一切都很好,除了我在線上發生錯誤:let date = UIImagePngRepresentation(image)。它說「不能將類型UIImageView轉換爲類型UIImage」 –

+0

檢查我的編輯。 'let data = UIImagePNGRepresentation(pickedImage)' –

+1

抱歉我的頁面沒有刷新。但它現在工作了!非常感謝你 –

相關問題