【问题标题】:Get title of YouTube video using YouTubeAPI使用 YouTube API 获取 YouTube 视频的标题
【发布时间】:2017-10-14 12:18:32
【问题描述】:

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

    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 会说:

对成员“下标”的不明确引用。

如何获取视频的标题?

谢谢!

【问题讨论】:

    标签: ios json swift youtube-api


    【解决方案1】:

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

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

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

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

    尽管如此,如果您的字典是基于字符串的,那么您应该键入它无论如何都使用String 键:)


    顺便说一句,[Key: Value] 只是 语法糖 用于更长的 Dictionary&lt;Key, Value&gt; 显式类型名称。

    【讨论】:

      猜你喜欢
      • 2011-01-29
      • 2013-04-23
      • 2015-10-23
      • 2017-12-10
      • 2018-01-30
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多