Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 642
Bartłomiej Semańczyk Avatar asked Nov 29 '25 00:11

Bartłomiej Semańczyk


1 Answers

  • 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)
    }
    
like image 82
Dipen Panchasara Avatar answered Nov 30 '25 15:11

Dipen Panchasara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!