【问题标题】:How to print a list of video titles from a YouTube channel with Swift 3?如何使用 Swift 3 从 YouTube 频道打印视频标题列表?
【发布时间】:2017-12-17 05:34:15
【问题描述】:

我想打印“items”、“sn-p”中的每个“标题”,但我的 for 循环由于某种原因没有执行。如果有人可以帮助我,请提前致谢。

代码:

let url = URL(string: "https://www.googleapis.com/youtube/v3/search?key=\(key)&channelId=\(channelID)&part=snippet,id&order=date&maxResults=20")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

        if error != nil {
            print("ERROR")
        } else {
            if let content = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(json)

                    for _ in json as! [String: AnyObject] {
                        if let items = json["items"] as? NSDictionary {
                            print(items)

                            if let snippet = items["snippet"] as? NSDictionary {
                                print(snippet)

                                if let title = snippet["title"] as? NSDictionary {
                                    print(title)
                                }
                            }

                        }
                    }

                } catch {
                    print("ERROR")
                }
            }
        }

    }
    task.resume()

JSON - 我把它缩短了很多,因为有一个限制 - 我从 Google 收到的是:

{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/VCbtvQebUdRw3e7_zJbfxm0jID4\"";
items =     (
            {
        etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/LEyFeYOSX6YKSwwyN5aSWbiKNcA\"";
        id =             {
            kind = "youtube#video";
            videoId = YT6G4Cg60xE;
        };
        kind = "youtube#searchResult";
        snippet =             {
            channelId = UCuP2vJ6kRutQBfRmdcI92mA;
            channelTitle = "Lets Build That App";
            description = "Facial detection is a new piece technology that's getting better and better over time. However, upon trying out Apple's new Vision API we can see that there is still ...";
            liveBroadcastContent = none;
            publishedAt = "2017-07-12T15:00:06.000Z";
            thumbnails =                 {
                default =                     {
                    height = 90;
                    url = "https://i.ytimg.com/vi/YT6G4Cg60xE/default.jpg";
                    width = 120;
                };
                high =                     {
                    height = 360;
                    url = "https://i.ytimg.com/vi/YT6G4Cg60xE/hqdefault.jpg";
                    width = 480;
                };
                medium =                     {
                    height = 180;
                    url = "https://i.ytimg.com/vi/YT6G4Cg60xE/mqdefault.jpg";
                    width = 320;
                };
            };
            title = "Is Apple's Vision Racially Biased?";
        };
    },
            {
        etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/zooINPhLwlR1Dm6MxGKbMzeFtMY\"";
        id =             {
            kind = "youtube#video";
            videoId = hPQIRIl977I;
        };
        kind = "youtube#searchResult";
        snippet =             {
            channelId = UCuP2vJ6kRutQBfRmdcI92mA;
            channelTitle = "Lets Build That App";
            description = "I often get questions about how I got started in programming and what kind of portfolio projects to include in a resume. Well, let me show you a video I uploaded ...";
            liveBroadcastContent = none;
            publishedAt = "2017-07-10T15:00:06.000Z";
            thumbnails =                 {
                default =                     {
                    height = 90;
                    url = "https://i.ytimg.com/vi/hPQIRIl977I/default.jpg";
                    width = 120;
                };
                high =                     {
                    height = 360;
                    url = "https://i.ytimg.com/vi/hPQIRIl977I/hqdefault.jpg";
                    width = 480;
                };
                medium =                     {
                    height = 180;
                    url = "https://i.ytimg.com/vi/hPQIRIl977I/mqdefault.jpg";
                    width = 320;
                };
            };
            title = "My First Portfolio Project when Applying for Software Jobs";
        };
    },
            {
        etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/n313rK9YZDxF118LMEo6i4X_Oz4\"";
        id =             {
            kind = "youtube#video";
            videoId = ZVCMV4a3KRw;
        };
        kind = "youtube#searchResult";
        snippet =             {
            channelId = UCuP2vJ6kRutQBfRmdcI92mA;
            channelTitle = "Lets Build That App";
            description = "Often times I take questions from you guys that watch the channel and today I wanted to flip the script and get some input. I'm genuinely curious about what you ...";
            liveBroadcastContent = none;
            publishedAt = "2017-07-09T19:42:59.000Z";
            thumbnails =                 {
                default =                     {
                    height = 90;
                    url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/default.jpg";
                    width = 120;
                };
                high =                     {
                    height = 360;
                    url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/hqdefault.jpg";
                    width = 480;
                };
                medium =                     {
                    height = 180;
                    url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/mqdefault.jpg";
                    width = 320;
                };
            };
            title = "Why do you guys watch the live stream?";
        };
    },
            {
        etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/Q38Ub7-kDjTpoE407EG2kKc50xo\"";
        id =             {
            kind = "youtube#video";
            videoId = d0U5j89M6aI;
        };
        kind = "youtube#searchResult";
        snippet =             {
            channelId = UCuP2vJ6kRutQBfRmdcI92mA;
            channelTitle = "Lets Build That App";
            description = "Face detection has been available through 3rd party APIs for a while now. Finally we have native support for this feature using Vision APIs with Xcode 9 and ...";
            liveBroadcastContent = none;
            publishedAt = "2017-07-08T15:00:06.000Z";
            thumbnails =                 {
                default =                     {
                    height = 90;
                    url = "https://i.ytimg.com/vi/d0U5j89M6aI/default.jpg";
                    width = 120;
                };
                high =                     {
                    height = 360;
                    url = "https://i.ytimg.com/vi/d0U5j89M6aI/hqdefault.jpg";
                    width = 480;
                };
                medium =                     {
                    height = 180;
                    url = "https://i.ytimg.com/vi/d0U5j89M6aI/mqdefault.jpg";
                    width = 320;
                };
            };
            title = "Super Impressive and Easy Face Detection using Vision API in Swift 4";
        };
    },
            {
        etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/ZADZ11_Ev4ItFjXj09gohLZCoMU\"";
        id =             {
            kind = "youtube#video";
            videoId = 1RMkGkL9L3U;
        };
        kind = "youtube#searchResult";
        snippet =             {
            channelId = UCuP2vJ6kRutQBfRmdcI92mA;
            channelTitle = "Lets Build That App";
            description = "Today we answer a question on how helpful Udemy, Udacity, or formal education from colleges are when it comes to learning new skills required for contracting ...";
            liveBroadcastContent = none;
            publishedAt = "2017-07-05T15:00:01.000Z";
            thumbnails =                 {
                default =                     {
                    height = 90;
                    url = "https://i.ytimg.com/vi/1RMkGkL9L3U/default.jpg";
                    width = 120;
                };
                high =                     {
                    height = 360;
                    url = "https://i.ytimg.com/vi/1RMkGkL9L3U/hqdefault.jpg";
                    width = 480;
                };
                medium =                     {
                    height = 180;
                    url = "https://i.ytimg.com/vi/1RMkGkL9L3U/mqdefault.jpg";
                    width = 320;
                };
            };
            title = "How I Learn New Skills for the Job - Udemy, Udacity, College, Google?";
        };
    },

【问题讨论】:

    标签: ios swift youtube-api


    【解决方案1】:

    首先,不要在 Swift 中使用 NSDictioanryNSArray,而是使用 Swift 原生类型 Dictionary([:])Array([]),因为使用此编译器将很容易理解值对象的类型。同样在 Swift 中,不需要指定 mutableContainers 选项,要获得可变对象,您只需使用 var 声明它。

    现在在您的 JSON 响应中,itemsArrayDictionary 而不是直接 Dictionarytitlesnippet 这个项目数组的每个 dictionary 的字典中,所以你需要循环遍历 items 数组,而不是循环遍历 JSON

    if let content = data {
        if let json = (try? JSONSerialization.jsonObject(with: content, options: [])) as? [String:Any],
           let items = json["items"] as? [[String:Any]] {
    
             for item in items {
                 if let snippet = item["snippet"] as? [String:Any],
                    let title = snippet["title"] as? String {
    
                       print(title)
                 }
             } 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2012-10-24
      • 2021-09-05
      • 2013-05-14
      • 2022-01-27
      • 2015-10-24
      • 2020-04-10
      • 2018-06-11
      • 1970-01-01
      相关资源
      最近更新 更多