Swift UIImagePickerController 动态转换获取路径失败

Swift UIImagePickerController dynamic cast failed in getting path

我正在尝试从 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 键将 return UIImage 而不是所选图像的 NSURL

如果你需要引用 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.

引用UIImagePickerControllerDelegate Protocol Reference