【问题标题】:Use youtube api to get video list with swift 3使用 youtube api 通过 swift 3 获取视频列表
【发布时间】:2017-10-13 12:56:22
【问题描述】:

我想取回频道视频的标题和 ID,但我在 JSON 级别阻止。它的效果是,当我尝试制作 MYJSONARRAY ["items"] [0] 时,没有任何显示:/ 谢谢你的帮助:)

let url = URL(string: "https://www.googleapis.com/youtube/v3/search?key=**************Q&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{
                    let myJsonArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(myJsonArray["items"][0]) //NOT WORKING
                    //let test1 = myJsonArray["items"]
                    //print(myJsonArray)
                    print("\n \n --------------------- \n \n")
                    if let items = myJsonArray["items"] as? NSDictionary{
                        print(items) // NOT WORKING
                    }

                }catch{

                }
            }
        }

    }
    task.resume()

api的答案:https://pastebin.com/uWhmmJcm

谢谢你:)

【问题讨论】:

    标签: ios json swift youtube-api


    【解决方案1】:

    您没有正确转换,AnyObject 不适合 JSON 响应的转换,它通常是字典项的数组。

    改变这一行..

    let myJsonArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
    

    if let myJsonArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] {
    
    //Now it's working
    
       if let items = myJsonArray["items"] as? [[String:Any]] {
           for item in items {
               print(item)
           }  
       }
    }
    

    【讨论】:

    • 好的,谢谢,但是 Xcode 说“不能使用 'String' 类型的索引来下标 '[[String : Any]]' 类型的值” 谢谢 :)
    • 好的,我将 [[String:Any]] 更改为 [String:Any],现在可以使用了,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2016-01-17
    • 1970-01-01
    • 2023-03-30
    • 2012-06-23
    • 2016-03-13
    • 2015-11-11
    • 2014-05-02
    相关资源
    最近更新 更多