Swift 3.0获取从UIImagePickerController中选择的UIImage的URL [英] Swift 3.0 Getting URL of UIImage selected from UIImagePickerController

查看:247
本文介绍了Swift 3.0获取从UIImagePickerController中选择的UIImage的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:-此问题仅适用于Swift 3.0 我能够获得到Swift 3.0的prio路径

Note:- This question is only for Swift 3.0 I am able to get the path prio to Swift 3.0

我想在 didFinishPickingMediaWithInfo 方法中选择UIImage的路径

I want to get UIImage's path picked in didFinishPickingMediaWithInfo method

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

但是此路径未指向我的图像,即使文档"文件夹中没有任何图像.

But this path is not pointing to my image, Even there is no any image in Documents folder.

有人可以帮我吗?

推荐答案

您不能直接访问所选图像的路径.您需要将其保存在DocumentsDirectory中,然后将图像和路径一起拿回.

You can't access the path of the picked image directly. You need to save that in your DocumentsDirectory and then take the image back with the path.

执行此操作

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中一次,因为它将在下次找到该路径.

Also note that you are using the name as the last path component which is same for every file. So, this will save your image in DocumentDirectory only once as it will find the path next time.

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

Now when you access the localPath variable and navigate to the path, you will find the image.

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

NOTE:
If you are using a device here, then you need to download the container of the device, show its package contents and navigate to the Documents Directory where you will find your saved image.

这篇关于Swift 3.0获取从UIImagePickerController中选择的UIImage的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆