保存用户选择iOS的图像

时间:2015-01-22 11:35:57

标签: ios iphone image swift uiimageview

我的应用中有个人资料标签。当我打开标签时,我看到了正常的图像。 可以从相机胶卷中选择图像。 代码:

 func selectImage()
    {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){

            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            imagePicker.allowsEditing = false

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

    }

当用户选择图像时,它被设置为imageView

       func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
            self.dismissViewControllerAnimated(true, completion: { () -> Void in

            })
            userImage.image = image

        }

如何在下次用户打开应用时保存此图片? 我只发现了一个使用NSUserDefaults的SO问题,但他们说这不推荐。

保存文件路径更好吗?如果是这样,我该如何管理?

1 个答案:

答案 0 :(得分:0)

为了将图像保存到文件路径,请使用以下代码

let fileDirectory = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true)

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
        self.dismissViewControllerAnimated(true, completion: { () -> Void in

        })
        userImage.image = image
        var imageData = UIImageJPEGRepresentation(image, 1.0)
        var imageFilePath = fileDirectory[0].stringByAppendingPathComponent("userPicture.jpeg")
        var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
        imageData.writeToURL(imageFileURL!, atomically: false)
}

要从保存的本地文件设置图像,您必须首先检查该文件是否存在,然后将其内容加载到图像视图

override func viewDidLoad() {

var imagePath = fileDirectory[0].stringByAppendingPathComponent("userPicture.jpeg")

var fileManager = NSFileManager.defaultManager()

    if (fileManager.fileExistsAtPath(imagePath)){

            userImage.image =  UIImage(contentsOfFile : imagePath)

    }
}