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

时间:2015-03-07 04:00:38

标签: 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上显示,但我无法获取它的网址。

这是我写的代码来获取它。

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,它也会崩溃。

我们不能直接访问网址,如果不是UIImagePickerControllerReferenceURL应该返回的内容吗?

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

由于

1 个答案:

答案 0 :(得分:1)

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中搜索给定的图像名称,找出完整的图像路径,然后设置为图像视图。