如何在 Swift 3.1 中使用 UIImagePickerControllerDelegate 获取目录(本地路径)?

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

我将使用委托方法从 UIImagepicker 中获取照片目录。但是我不知道该怎么做所以给我提示这个问题

这行你可以得到你照片在swift3++中的路径:

let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL

您可以在委托函数中使用它 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

代码:

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