我正在使用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中。有什么办法解决这个问题吗?
发布于 2017-07-30 06:02:42
请不要使用强制式铸造。它可能会导致应用程序崩溃。总是使用如果让或守卫让。试着像这样迭代
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)
}
}
}}
发布于 2017-07-30 01:21:37
这意味着您在字典中没有项的值,或者您正在不正确地访问它。
发布于 2017-07-30 01:26:14
你想要向NSArray施展力量。如果dictionary["items"]不是NSArray,这将使你的应用程序崩溃。
我建议您在循环之前放置一个断点,以检查dictionary["items"]的类型。
示例:
guard let items = dictionary["items"] as? NSArray else { return }https://stackoverflow.com/questions/45395446
复制相似问题