May*_*ain 6 nsurl filepath ios swift swift3
注意: - 这个问题仅适用于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!)
Run Code Online (Sandbox Code Playgroud)
但是这条路径并没有指向我的图像,即使文档文件夹中没有任何图像.
谁可以帮我这个事?
Raj*_*ari 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")
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您使用名称作为最后一个路径组件,对于每个文件都是相同的.因此,这将仅在DocumentDirectory中保存您的图像一次,因为它将在下次找到路径.
现在,当您访问localPath变量并导航到路径时,您将找到该图像.
注意:
如果您在此处使用设备,则需要下载设备的容器,显示其包装内容并导航到文档目录,您将在其中找到保存的图像.
| 归档时间: |
|
| 查看次数: |
10428 次 |
| 最近记录: |