我使用YouTube数据API和Alamofire显示我的YouTube频道视频,并动态更新。这是我的代码:
func getFeedVideo() {
Alamofire.request("https://www.googleapis.com/youtube/v3/playlists", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let JSON = response.result.value {
if let dictionary = JSON as? [String: Any] {
var arrayOfVideos = [Video]()
for video in dictionary["items"] as! NSArray {
// Create video objects off of the JSON response
let videoObj = Video()
videoObj.videoID = (video as AnyObject).value(forKeyPath: "snippet.resourceId.videoId") as! String
videoObj.videoTitle = (video as AnyObject).value(forKeyPath: "snippet.title") as! String
videoObj.videoDescription = (video as AnyObject).value(forKeyPath: "snippet.description") as! String
videoObj.videoThumbnailUrl = (video as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
}
我收到错误
主题1:EXC_BAD_INSTRUCTION
在for video in dictionary["items"] as! NSArray {
行。在控制台中,我看到了
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
数据显示在UITableView
中。关于如何解决这个问题的任何想法?
答案 0 :(得分:1)
请不要使用强制类型演员。它可能会导致您的应用崩溃。如果让或保护让我们使用。尝试像那样迭代它
if let dictionary = JSON as? [String: Any] {
var arrayOfVideos = [Video]()
if let playlist = dictionary["items"] as? [Any] {
for i in 0..<playlist.count {
let videoObj = Video()
if let video = playlist[i] as? [String: Any] {
if let videoId = video["id"] as? String {
videoObj.videoID = videoId
}
if let snippet = video["snippet"] as? [String: Any] {
if let videoTitle = snippet["title"] as? String {
videoObj.videoTitle = videoTitle
}
if let videoDescription = snippet["description"] as? String {
videoObj.videoDescription = videoDescription
}
}
if let thumbnails = video["thumbnails"] as? [String: Any]{
if let maxres = thumbnails["maxres"] as? [String: Any] {
if let url = maxres["url"] as? String {
videoObj.videoThumbnailUrl = url
}
}
}
arrayOfVideos.append(videoObj)
}
}
}
}
答案 1 :(得分:0)
这意味着您没有字典中的项目值,或者您正在不正确地访问它。
答案 2 :(得分:0)
你正试图向NSArray施放一股力量。如果dictionary["items"]
不是NSArray,这将使您的应用程序崩溃
我建议你在循环之前设置一个断点来检查dictionary["items"]
的类型。
示例:强>
guard let items = dictionary["items"] as? NSArray else { return }