Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

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?

Upvotes: 2

Views: 8128

Answers (3)

Gurjinder Singh
Gurjinder Singh

Reputation: 10299

Swift 5

func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        guard let image = info[.editedImage] as? UIImage else {
            print("No image found")
            return
        }
        // saving to application directory
        let imageName = UUID().uuidString
        let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
        if let jpegData = image.jpegData(compressionQuality: 0.8) {
            print("Image Save to path \(imagePath)")
            try? jpegData.write(to: imagePath)
        }
     }

Upvotes: 1

Ricardo Gonçalves
Ricardo Gonçalves

Reputation: 5074

Updating the accepted answer to Swift 3 in Xcode 8.3.3

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
        let newPath = path.appendingPathComponent("image.jpg")
        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
        do {
            try jpgImageData!.write(to: newPath)
        } catch {
            print(error)
        }

    } else {
        let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
        let videoData = NSData(contentsOf: videoURL as URL)
        let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
        let newPath = path.appendingPathComponent("/videoFileName.mp4")
        do {
            try videoData?.write(to: newPath)
        } catch {
            print(error)
        }
    }
}

Upvotes: 6

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

  • 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)
    }
    

Upvotes: 12

Related Questions