错误:无法分配“AnyObject”类型的值?值为'NSURL'的值

时间:2015-11-20 11:59:16

标签: ios iphone swift

获取错误:无法指定“AnyObject”类型的值?到'NSURL'类型的值

我的代码:

var videoPlayer = MPMoviePlayerController()
    var mediaUI = UIImagePickerController()
    var videoURL = NSURL()



 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){

              // error in below first line

        self.videoURL = info[UIImagePickerControllerMediaURL]
      mediaUI.dismissViewControllerAnimated(true, completion: nil)
        self.videoPlayer = MPMoviePlayerController()
        self.videoPlayer.contentURL = videoURL
        self.videoPlayer.view.frame = CGRectMake(0,0,self.view.frame.size.width,460)
        self.view.addSubview(self.videoPlayer.view)
        self.videoPlayer.play()

         }

如何更改该代码以解决我的错误。

1 个答案:

答案 0 :(得分:2)

info[UIImagePickerControllerMediaURL]的类型为AnyObject?,但self.videoURL的类型为NSURL

安全地将结果转换为NSURL:

if let vURL = info[UIImagePickerControllerMediaURL] as? NSURL {
    self.videoURL = vURL
}

这是你修改的代码:

var videoPlayer = MPMoviePlayerController()
var mediaUI = UIImagePickerController()
var videoURL = NSURL()

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    if let vURL = info[UIImagePickerControllerMediaURL] as? NSURL {
        self.videoURL = vURL
    } else {
        print("oops, no url")
    }
    mediaUI.dismissViewControllerAnimated(true, completion: nil)
    self.videoPlayer = MPMoviePlayerController()
    self.videoPlayer.contentURL = videoURL
    self.videoPlayer.view.frame = CGRectMake(0,0,self.view.frame.size.width,460)
    self.view.addSubview(self.videoPlayer.view)
    self.videoPlayer.play()

}