Search code examples
iosiphoneswiftswift3uiimagepickercontroller

How to fetch Directory(localpath) using UIImagePickerControllerDelegate in Swift 3.1?


I going to fetch directory of photo From UIImagepicker using delegates method. but how to do this i don't know so give me hint for this isssue


Solution

  • This line you can get the path of your photo in swift 3++:

    let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL
    

    You can use it in delegate function func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

    Code:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        // get image url
        let imageUrl          = info[UIImagePickerControllerReferenceURL] as? NSURL
        let imageName         = imageUrl?.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let photoURL          = NSURL(fileURLWithPath: documentDirectory)
        let localPath         = photoURL.appendingPathComponent(imageName!)
    
        if !FileManager.default.fileExists(atPath: localPath!.path) {
            do {
                try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
                print("file saved")
            }catch {
                print("error saving file")
            }
        }
        else {
            print("file already exists")
        }
    }