ios - 使用 YouTube API 获取 YouTube 视频的标题

标签 ios json swift youtube-api

我正在使用 YouTube API 从 channel 获取视频,我想获取标题:

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?key=**********&channelId=UCFNHx0ppCqm4EgPzEcOc29Q&part=snippet,id&order=date&maxResults=50")
    let task = URLSession.shared.dataTask(with: url!) { (data, reponse, error) in

        if error != nil {
            print("ERROR")
        }else{
            if let content = data {
                do{
                    if let myJsonArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] {
                        if let itemsJson = myJsonArray["items"] as? [[String:Any]] {
                            //var i:Int = 0

                            for i in 0 ..< itemsJson.count {
                                 print("-----------------------------")
                                let snippetDict = itemsJson[i]["snippet"] as! Dictionary<NSObject, AnyObject>
                                print(snippetDict["title"] as String) //NOT WORKING
                             }
                        }
                    }
                }catch{
                    print("ERROR 2")
                }
            }
        }

    }
    task.resume()

但是当我将所有标题打印为 print(snippetDict["title"] as String) 时,Xcode 说:

ambiguous reference to member 'subscript'`.

如何获取视频的标题?

谢谢!

最佳答案

尝试使用 String作为您的 key (而不是 NSObject ):

let snippetDict = itemsJson[i]["snippet"] as! [String: AnyObject]

我怀疑冲突是由这两个引起的Dictionary 下标(当使用 String 作为键时):

subscript(key: NSObject) -> Value?
subscript(key: _Hashable) -> Value?

不过,如果您的字典是基于字符串的,那么您应该使用String键入它。反正 key :)


顺便说一句,[Key: Value]只是语法糖更长的Dictionary<Key, Value>明确的类型名称。

关于ios - 使用 YouTube API 获取 YouTube 视频的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43984138/

相关文章:

ios - 特征集合中每个特征的不同图标

ios - 使用 NSJSONSerialization 序列化一个 unsigned long long

ios - 从较大的 UIImage 中裁剪一部分 UIImage,并包括非图像部分

jquery - 从 JSON 更新 Django 中的数据表

java - 不能在 Android Studio 项目中包含 JSONParser

ios 8 swift - 如何使用单独的数据源为 tableview 添加页脚

javascript - 使用 JSON 和 jQuery 的编码问题

ios - Swift:无法将 NSNumber 类型转换为预期的参数类型 Int16

ios - 自定义 header "fatal error: unexpectedly found nil while unwrapping an Optional value"

Swift TableViewDataSource 分离其他类