Tristan Diependael
Tristan Diependael

Reputation: 623

How to print a list of video titles from a YouTube channel with Swift 3?

I want to print every "title" in "items", "snippet", but my for-loop isn't executing for some reason. If someone can help me, thanks in advance.

code:

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

the JSON -I made it a lot shorter because there is a limit- I receive from Google is:

{
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?";
        };
    },

Upvotes: 1

Views: 1135

Answers (1)

Nirav D
Nirav D

Reputation: 72420

First of all don't use NSDictioanry and NSArray in Swift instead of that use Swift native type Dictionary([:]) and Array([]) because with this compiler will easily understand what type of value object having. Also in Swift there is no need to specify mutableContainers option, to get mutable object you need to simply declare it with var.

Now in your JSON response items is Array of Dictionary not directly Dictionary and title is inside the snippet dictionary of each dictionary of this items array, so you need to loop through the items array instead of loop through the 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)
             }
         } 
    }
}

Upvotes: 2

Related Questions