获取UIImagePickerController中所选UIImage的URL(Swift 3.0)

6

注意:此问题仅适用于Swift 3.0。

在Swift 3.0之前,我能够获取路径。

我想在didFinishPickingMediaWithInfo方法中获取选定的UIImage的路径。

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!)

但是这个路径并没有指向我的图像,即使在文档文件夹中也没有任何图像。
有人能帮我吗?

被调用的方法是什么?记录变量,特别是imageUrl - shallowThought
@MayankJain 当图片根本没有存储在DocumentDirectory中时,它如何指向图片?现在告诉我你想要实现什么。 - Rajan Maheshwari
2个回答

12

您无法直接访问选择的图像路径。您需要将其保存在DocumentsDirectory中,然后使用路径取回该图像。

请执行以下操作:

Swift 3.x

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    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")
    }
}

请注意,您正在使用名称作为最后一个路径组件,每个文件的名称都相同。因此,下次查找路径时,此操作将仅在DocumentDirectory中保存您的图像一次。

现在,当您访问localPath变量并导航到该路径时,您将找到该图像。

注意:
如果您正在使用设备,则需要下载设备的容器,显示其包内容并导航到文档目录,其中您将找到已保存的图像。


2
SWIFT 4中,您可以尝试这个,它可以正常运行。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


    if let imgUrl = info[UIImagePickerControllerImageURL] as? URL{
        let imgName = imgUrl.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let localPath = documentDirectory?.appending(imgName)

        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let data = UIImagePNGRepresentation(image)! as NSData
        data.write(toFile: localPath!, atomically: true)
        //let imageData = NSData(contentsOfFile: localPath!)!
        let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
        print(photoURL)

    }

    APPDEL.window?.rootViewController?.dismiss(animated: true, completion: nil)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接