我正在尝试从 UIImagePicker
获取照片的路径,当我尝试获取它时出现“Swift dynamic cast failed”。这是我的代码:
@IBAction func addPhotoButton(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
在这里我得到了路径:
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismissViewControllerAnimated(true, completion: { () -> Void in
var path: NSURL = editingInfo.valueForKeyPath("UIImagePickerControllerOriginalImage") as NSURL
println(path)
})
}
当我尝试获取 var path
的值时,应用程序崩溃了
最佳答案
UIImagePickerControllerOriginalImage
键将返回一个 UIImage
而不是所选图像的 NSURL
。
如果你需要referece url,你需要使用UIImagePickerControllerReferenceURL
键。
更改以下代码:
var path: NSURL = editingInfo.valueForKeyPath("UIImagePickerControllerOriginalImage") as NSURL
到:
var path: NSURL = editingInfo.valueForKey("UIImagePickerControllerReferenceURL") as NSURL
UIImagePickerControllerOriginalImage
Specifies the original, uncropped image selected by the user.
The value for this key is a
UIImage
object.
UIImagePickerControllerReferenceURL
The Assets Library URL for the original version of the picked item.
After the user edits a picked item—such as by cropping an image or trimming a movie—the URL continues to point to the original version of the picked item.
The value for this key is an
NSURL
object.
关于ios - Swift UIImagePickerController 动态转换获取路径失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595634/