ios - 如何获取 iOS Swift 图片库图像的 URL?

标签 ios swift uiimagepickercontroller

我正在为 UIImagePickerController 编写如下代码,以从照片库中获取图像。

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
    // Code here

    var imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
    imagePicker.mediaTypes = [kUTTypeImage]
    imagePicker.allowsEditing = false

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

选择图像后,我可以在 UIImageView 上显示它,但无法获取它的 URL。

这是我为获取它而编写的代码。

let url: NSString = info[UIImagePickerControllerReferenceURL] as NSString

var imageName:String = url.lastPathComponent        
println("URL is \(imageName)")

let image = info[UIImagePickerControllerOriginalImage] as UIImage
profileImage.image =  image
self.dismissViewControllerAnimated(true, completion: nil)

这里它给出了nil,如果我使用UIImagePickerControllerEditedImage,它也会崩溃。

我们不能直接访问 URL,如果不是的话 UIImagePickerControllerReferenceURL 应该返回什么?

如何获取图像的 URL,以便将其发送到服务器。

谢谢

最佳答案

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask

if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
    if paths.count > 0 {
        if let dirPath = paths[0] as? String {
            let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
            var pickedimage = UIImage(CGImage: UIImage(contentsOfFile: readPath)!.CGImage, scale: 1.0, orientation: .Up)

            UploadImagePreview.image = pickedimage
        }
    }
}

注意:如果知道完整地址,我们可以从url设置图片。这里我们在 nsDocumentDirectory 中搜索给定的图像名称,找出完整的图像路径,然后设置为 ImageView 。

关于ios - 如何获取 iOS Swift 图片库图像的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911217/

相关文章:

ios - 如何在核心数据中存储数组(Swift)

ios - 详细 View UITableView - 在 segue 之前传递数据

ios - UiImagePicker 自定义部分

ios - 从 UITableViewCell iOS 打开相机

ios - 如何在 IOS 上去除图像的方形比例裁剪

ios - 扑克手排名循环组合

iOS StoreKit 应用程序(应用程序内购买应用程序)- 互联网不可用时

ios - 如何创建枚举类型的 IBInspectable

ios - Swift 中的自定义输入 View

ios - 从按钮访问 View Controller