除非你改变它,你怎么能让照片永远留在那里?

时间:2016-08-09 14:12:29

标签: ios swift save nsuserdefaults

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    print("Image Uploaded")

    self.dismissViewControllerAnimated(true, completion: nil)

    filterimage.image = image   
}

@IBAction func importImage(sender: AnyObject) {
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.Camera

    image.allowsEditing = false

    self.presentViewController(image, animated: true, completion: nil)
}

关闭应用程序并再次打开它后,图像将消失。如何在我再次打开应用程序时将图像保留在那里。我知道怎么用NSUserDefaults的文字来做这件事,但你怎么用图像做呢?

2 个答案:

答案 0 :(得分:1)

您希望将其保存到Documents目录,如下所示:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    print("Image Uploaded")
    saveImageToDirectory(image)
    self.dismissViewControllerAnimated(true, completion: nil)  
}

func saveImageToDirectory(image : UIImage) {
    if let data = UIImageJPEGRepresentation(image, 1.0) {
        let filename = getDocumentsDirectory().stringByAppendingPathComponent("myCameraImage.png")
        data.writeToFile(filename, atomically: true)
    }
}

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

//To retrieve the image...
func getImage() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let getImagePath = paths.stringByAppendingPathComponent("myCameraImage.jpg")
    let image = UIImage(contentsOfFile: getImagePath)
    print(image)
}

归功于Hacking With Swift

答案 1 :(得分:0)

editingInfo字典会告诉您所选图像的源URL(UIImagePickerControllerReferenceURL)。保存这些信息,以便以后再次使用它来获取相同的图像。