类型为 'Any' 的值没有成员'valueForKeyPath'



我正在寻找其他堆栈溢出问题,但似乎它不适用于我的情况。

我正在制作YouTube应用程序,我的代码如下。

if let JSON = response.result.value as? NSDictionary{
var arrayOfVideos = [Video]()
for video in JSON["items"] as! NSArray{
print(video)
//Create video onjects off of the JSON response
let videoObj = Video()
//I got errors following part
videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as! String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as! String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
}else{
print("couldn't get video information")
}

我还有一个定义标题,描述和缩略图的类视频。

class Video: NSObject {
var videoId:String = ""
var videoTitle:String = ""
var videoDescription:String = ""
var videoThumbnailUrl:String = ""
}

我得到了这些错误。

类型为"任何"的值没有成员"值为键路径">

还有这个

线程 1:致命错误:解开可选值时意外发现 nil

我感谢任何帮助。提前谢谢你。

你可以试试

if let JSON = response.result.value as? [String:Any] {
var arrayOfVideos = [Video]()
if let videos = JSON["items"] as? [[String:Any]] {
for video in videos {
let videoObj = Video()
if let videoId = video["snippet.resourceId.videoId"] as? String {
videoObj.videoId = videoId 
}
if let videoTitle = video["snippet.title"] as? String {
videoObj.videoTitle = videoTitle
}
if let videoDescription = video["snippet.description"] as? String {
videoObj.videoDescription = videoDescription
}
if let videoThumbnailUrl = video["snippet.thumbnails.maxres.url"] as? String {
videoObj.videoThumbnailUrl = videoThumbnailUrl
}
arrayOfVideos.append(videoObj)
}
}
}       

最新更新