我编码如下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以便将其发送到服务器。
由于
答案 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中搜索给定的图像名称,找出完整的图像路径,然后设置为图像视图。