gpt4 book ai didi

ios - 使用 YouTube 数据 API 和 Alamofire 时出错

转载 作者:行者123 更新时间:2023-11-28 15:25:00 26 4
gpt4 key购买 nike

我正在使用 YouTube 数据 API 和 Alamofire 来显示我的 YouTube channel 的视频,它们会动态更新。这是我的代码:

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()
}
}
}
}
}

我遇到了一个错误

Thread 1: EXC_BAD_INSTRUCTION

在字典["items"] 中的视频中作为! NSArray {.在控制台中,我看到了

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

数据显示在 UITableView 中。关于如何解决此问题的任何想法?

最佳答案

请不要使用强制类型转换。这可能会导致您的应用程序崩溃。始终使用 if let 或 guard let。尝试像那样迭代它

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)
}
}
}

关于ios - 使用 YouTube 数据 API 和 Alamofire 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com