如何保存用户使用swift选择的图像?

时间:2015-04-01 14:43:07

标签: ios xcode swift camera uiimageview

在我正在制作的应用中,用户将选择一张照片,然后它将显示在图片视图中。如何保存他们在image.xcassets文件夹中选择的图像,所以当我重新启动应用程序时,图像仍然会在那里?

以下是我正在使用的代码......

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Action(sender: AnyObject) {

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {

            let imagePicker:UIImagePickerController = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
            imagePicker.allowsEditing = false

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




        }

    }






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




           self.dismissViewControllerAnimated(true, completion: nil)

            self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

//how do i save the image in the folder?
        }





    }

1 个答案:

答案 0 :(得分:2)

你可以这样做

var finalImage : UIImage()

//Your Method
func saveImage () {

       self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
       self.finalImage = self.imageView.image as UIImage

       let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
       let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
       if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {

       if paths.count > 0 {
         if let dirPath = paths[0] as? String {
         let readPath = dirPath.stringByAppendingPathComponent("Image.png")
         let image = UIImage(named: readPath)
         let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
         UIImagePNGRepresentation(self.finalImage).writeToFile(writePath, atomically: true)
    } 
  }
 }


}