获取错误:无法指定“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()
}
如何更改该代码以解决我的错误。
答案 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()
}