Pol
Pol

Reputation: 1351

Get title of YouTube video using YouTubeAPI

I am using the YouTube API to get videos from a channel and I would like to get title:

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

But when I print all titles as print(snippetDict["title"] as String), Xcode say:

ambiguous reference to member 'subscript'`.

How to get the title of videos?

Thank you !

Upvotes: 0

Views: 867

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Try using String as your key (instead of NSObject):

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

I suspect the conflict was arising from these two Dictionary subscripts (when using a String as key as you did):

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

Nevertheless, if your dictionary is string-based, than you should type it using String keys anyway :)


By the way, the [Key: Value] is just syntax sugar for the longer Dictionary<Key, Value> explicit type name.

Upvotes: 1

Related Questions