Swift 3.0获取从UIImagePickerController中选择的UIImage的URL

注意: – 这个问题仅适用于Swift 3.0我能够获得Swift 3.0的路径prio

我想在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!) 

但是这条路径并没有指向我的图像,即使文档文件夹中没有任何图像。

谁可以帮我这个事?

您无法直接访问所选图像的路径。 您需要将其保存在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变量并导航到路径时,您将找到该图像。

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

SWIFT 4 U Can试试这个,它正常工作。

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