Search code examples
iosswiftnsfilemanager

How to save image or video from UIPickerViewController to document directory?


  1. Handle selected image or video:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print("ok")
    
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //what to do to save that image
        } else {
            //how to get the video and save
        }
    }
    
  2. Save it to the document directory:

    let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
    let newPath = path.URLByAppendingPathComponent("image.jpg") //or video.mpg for example
    

How to save that image to following newPath?


Solution

    • Use following steps to save Image to documents directory

    Step 1: Get a path to document directory

    let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
    

    Step 2: Append FileName in path

    let newPath = path.stringByAppendingPathComponent("image.jpg")
    

    Step 3: Decide filetype of Image either JPEG or PNG and convert image to data(byte)

    //let pngImageData = UIImagePNGRepresentation(image) // if you want to save as PNG
    let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
    

    Step 4: write file to created path

    let result = jpgImageData!.writeToFile(newPath, atomically: true)
    

    Add above code into your didFinishPickingImage function.

    • Use following func to save video to documents directory

      func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) 
      {
          // *** store the video URL returned by UIImagePickerController *** //
          let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
      
          // *** load video data from URL *** //
          let videoData = NSData(contentsOfURL: videoURL)
      
          // *** Get documents directory path *** //
          let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
      
          // *** Append video file name *** //
          let dataPath = documentsDirectory.stringByAppendingPathComponent("/videoFileName.mp4")
      
          // *** Write video file data to path *** //
          videoData?.writeToFile(dataPath, atomically: false)
      }