如何使用NSDocument存储图像

时间:2016-01-25 11:57:39

标签: ios swift uiimageview nsdocument

如何使用NSDocument以编程方式在Swift iOS中存储图像?

    let alertController = UIAlertController(title: "Choose an option", message: "", preferredStyle: .Alert)

    let cameraRollAction = UIAlertAction(title: "Camera Roll", style: .Default) { (action) in
        self.imagePicker.delegate = self
        self.imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        self.imagePicker.allowsEditing = true
        self.presentViewController(self.imagePicker, animated: true, completion: nil)

    }
    alertController.addAction(cameraRollAction)

    let takePictureAction = UIAlertAction(title: "Take a picture", style: .Default) { (action) in
        self.imagePicker.delegate = self
        self.imagePicker.allowsEditing = true
        self.imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
        self.imagePicker.cameraCaptureMode = .Photo
        self.imagePicker.modalPresentationStyle = .FullScreen
        self.presentViewController(self.imagePicker,
            animated: true,
            completion: nil)
    }

我需要在选择按钮时存储图像,并在需要时检索它们。

1 个答案:

答案 0 :(得分:0)

实现UIImagePickerControllerDelegate的委托

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

let image = info[UIImagePickerControllerOriginalImage] as? UIImage
let imageData = UIImagePNGRepresentation(image!)
let dirPaths = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true)[0] as NSString

  let fullPath = dirPaths.stringByAppendingPathComponent("yourNameImg.png")
  let result = imageData.writeToFile(fullPath, atomically: true)
    dismissViewControllerAnimated(true, completion: nil) 

}