11

I'm trying to figure out how to use the new YouTube API (Version 3) in my iOS app but I don't know how to do it. I did many research about it but what I found is all examples and codes for older API so they are not valid. Til now I did understand that for using the new API you have to create a Project in Google Developer Console (and I did it)... but then they send you to a page with some code on it but I really don't understand how to use it. link to google api page What I need to know is how to retrieve some informations from a given URL of a YouTube video, the informations I need are total number of "likes" and total number of "views"... with API 2 it was very simple to do it... but now I really don't know where to begin... Is there someone that please can explain how to achieve this with maybe some examples and some code? I'm pretty sure that a lot of people will benefit from this.

JAL
  • 41,701
  • 23
  • 172
  • 300
Blue
  • 2,300
  • 3
  • 21
  • 32

3 Answers3

23

You don't have to use the iOS client Google provides to make those kinds of request.

  1. Navigate to the API Console and generate a new Simple API Access key for your iOS application. Be sure to enter your app's bundle identifier in the provided window. Alternatively, you can create a Server API key for testing with basic requests and curl from the command line.

  2. Find the relevant endpoint for your needs. To find information about a video, you'll want to use the Videos.list method.

First, set up you URL. I will be using this URL as an example: https://www.youtube.com/watch?v=AKiiekaEHhI

You're going to want to specify a value for the part parameter. From your question, it looks like you're going to want to pass in the snippet, contentDetails, and statistics values (although for likes and views, you really only need the statistics value).

Then pass in the id of your video (in this case AKiiekaEHhI, you can add up to 50 comma-separated IDs) and your API key. Your URL should look something like this :

https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}

You can also do this in the API Explorer.

Swift implementation:

// Set up your URL
let youtubeApi = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}"
let url = NSURL(string: youtubeApi)

// Create your request
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject] {

            print("Response from YouTube: \(jsonResult)")
        }
    }
    catch {
        print("json error: \(error)")
    }

})

// Start the request
task.resume()

Objective-C implementation:

(This post has been edited to support NSURLSession. For an implementation that uses NSURLConnection, check the edit history)

// Set up your URL
NSString *youtubeApi = @"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}";
NSURL *url = [[NSURL alloc] initWithString:youtubeApi];

// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {

    // Callback, parse the data and check for errors
    if (data && !connectionError) {
        NSError *jsonError;
        NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

        if (!jsonError) {
            NSLog(@"Response from YouTube: %@", jsonResult);
        }
    }
}] resume];

Your log will look something like this:

Response from YouTube: {
    etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/AAjIATmVK_8ySsAWwEuNfdZdjW4\"";
    items =     (
                {
            contentDetails =             {
                caption = false;
                definition = hd;
                dimension = 2d;
                duration = PT17M30S;
                licensedContent = 1;
            };
            etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/8v8ee5uPZQa1-ucVdjBdAVXzcZk\"";
            id = AKiiekaEHhI;
            kind = "youtube#video";
            snippet =             {
                categoryId = 20;
                channelId = UCkvdZX3SVgfDW8ghtP1L2Ug;
                channelTitle = "Swordless Link";
                description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
                liveBroadcastContent = none;
                localized =                 {
                    description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
                    title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
                };
                publishedAt = "2015-05-04T10:01:43.000Z";
                thumbnails =                 {
                    default =                     {
                        height = 90;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/default.jpg";
                        width = 120;
                    };
                    high =                     {
                        height = 360;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/hqdefault.jpg";
                        width = 480;
                    };
                    medium =                     {
                        height = 180;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/mqdefault.jpg";
                        width = 320;
                    };
                    standard =                     {
                        height = 480;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/sddefault.jpg";
                        width = 640;
                    };
                };
                title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
            };
            statistics =             {
                commentCount = 54;
                dislikeCount = 3;
                favoriteCount = 0;
                likeCount = 265;
                viewCount = 6356;
            };
        }
    );
    kind = "youtube#videoListResponse";
    pageInfo =     {
        resultsPerPage = 1;
        totalResults = 1;
    };
} with error: nil

The object for the items key will be an array of info for each video id you passed in to the request.

By digging into this response, you will be able to get the information you need. For example:

if let items = jsonResult["items"] as? [AnyObject]? {
    println(items?[0]["statistics"])
}

Will give you a dictionary of the video's statistics (where you can get the number of likes and the number of views).

{
    commentCount = 54;
    dislikeCount = 3;
    favoriteCount = 0;
    likeCount = 265;
    viewCount = 6356;
}

This same approach can be used with live events.

JAL
  • 41,701
  • 23
  • 172
  • 300
  • Hey! Thanks for your answer, I program with Objective c and Xcode, tomorrow I will try to use your informations in my project and let you know... Thanks for your help – Blue May 24 '15 at 18:46
  • @Blue You should really change the tags on your question then. iOS != Objective-C, and Xcode uses both Objective-C and Swift. Nevertheless, I have added an Objective-C implementation and requested an edit on your question to include the Objective-C tag. – JAL May 24 '15 at 22:27
  • @Blue any updates or questions? Please let me know if you need help with anything else. – JAL May 26 '15 at 04:34
  • Hi Jal, I'm trying your code and I'm facing these problems: 1) if I use a Api Access Key for iOS I always get an error 403 or sometimes 400... but using a Server Key everything works fine... so I guess I just can use that in my project? or is there any restriction with a Server Key? 2) I can not use the code for getting the statistics: if let items = jsonResult["items"] as? AnyObject]? { etc.... it gives me error... maybe this is code for swift? – Blue May 26 '15 at 08:46
  • Did you set up iOS API access? You don't need to include your API key if you do. And that `if let` is swift. You probably want something like `jsonResult["items"][0]["statistics"]` to get into the nested dictionary inside of the array. – JAL May 26 '15 at 13:35
  • Ok, I'm almost there... deal with me just a little bit more... :D.... I have the data in a string format... so I transform it in data: 'NSString *strData = jsonResult[@"items"][0][@"statistics"]; NSData *jsonData = [NSKeyedArchiver archivedDataWithRootObject:strData];' then I make the dictionary 'NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];' and I try to find my objectForKey ' NSDictionary *data1; if (jsonData != nil) data1 = [dataDictionary objectForKey:@"items"]; ' but data1 is null.. what's wrong? – Blue May 26 '15 at 14:41
  • @Blue The object for the `statistics` key is a dictionary, you don't need to serialize it again. So `jsonResult[@"items"][0][@"statistics"][@"likeCount"]` will give you your like count. – JAL May 26 '15 at 17:03
  • Thanks so much brother, I got it working now... I just didn't understand how to set up iOS API access... where to do it and how... anyway thanks a lot for your help... I will give you the bounty... – Blue May 26 '15 at 17:17
  • My pleasure to help, happy hacking! – JAL May 26 '15 at 17:30
  • @JAL is it possible to upload to youtube directly from swift rather than just retrieving data? I can't see any examples online? Also then, would we retrieve a link back which I can post up to my own web service and store the link in a table along with all my other requirements? – user2363025 Jan 20 '16 at 14:46
  • @user2363025 what do you mean "directly from swift rather than just retrieving data?" You should ask a new question. – JAL Jan 20 '16 at 14:47
  • @JAL uploading a video to youttube rather than downloading what's already on there?...in the swift language – user2363025 Jan 20 '16 at 15:07
  • @user2363025 http://stackoverflow.com/q/3528568/2415822. If that doesn't help you should ask a new question – JAL Jan 20 '16 at 15:09
  • @JAL thanks, I'll get working on a question so as I can't see any swift samples there and the answer directs us to the old API 2.0 which is now deprecated.. – user2363025 Jan 20 '16 at 15:14
  • @JAL http://stackoverflow.com/questions/34904374/uploading-a-video-to-youtube-from-my-swift-app – user2363025 Jan 20 '16 at 15:43
  • @JAL Where did you learn all this stuff? I was looking for Swift documentation in the YouTube API and found nothing... '-' – Thi G. Feb 14 '16 at 03:48
  • @user2363025 re your question, that's a little broad for Stack Overflow. If you have a more specific programming question about the YouTube APIs, I'd be happy to answer it. – JAL Feb 14 '16 at 03:50
  • 1
    @ThiG. I learned this stuff by just reading the docs. I don't think Google provides any Swift-specific examples, so I just am making calls to their REST API. – JAL Feb 14 '16 at 03:50
  • Any ideas how to create a new playlist for the user after signing them in with OAuth2? http://stackoverflow.com/questions/36927062/create-playlist-in-youtube-api – abcf Apr 29 '16 at 11:53
7

// Swift 3

func search() {


   let videoType = "video you want to search"

    // can use any text


    var dataArray = [[String: AnyObject]]()
    // store videoid , thumbnial , Title , Description

    var apiKey = "_________________"

     // create api key from google developer console for youtube



        var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(videoType)&type=video&videoSyndicated=true&chart=mostPopular&maxResults=10&safeSearch=strict&order=relevance&order=viewCount&type=video&relevanceLanguage=en&regionCode=GB&key=\(apiKey)"



        urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
        let targetURL = URL(string: urlString)

        let config = URLSessionConfiguration.default // Session Configuration
        let session = URLSession(configuration: config)

        let task = session.dataTask(with: targetURL!) {

            data, response, error in


            if error != nil {

                print(error!.localizedDescription)


                var alert = UIAlertView(title: "alert", message: "No data.", delegate: nil, cancelButtonTitle: "OK")
                alert.show()



                return

            }

            else {




                do {





                    typealias JSONObject = [String:AnyObject]

                    let  json = try JSONSerialization.jsonObject(with: data!, options: []) as! JSONObject
                    let items  = json["items"] as! Array<JSONObject>



                    for i in 0 ..< items.count {

                        let snippetDictionary = items[i]["snippet"] as! JSONObject
                        print(snippetDictionary)
                        // Initialize a new dictionary and store the data of interest.
                        var youVideoDict = JSONObject()

                        youVideoDict["title"] = snippetDictionary["title"]
                        youVideoDict["channelTitle"] = snippetDictionary["channelTitle"]
                        youVideoDict["thumbnail"] = ((snippetDictionary["thumbnails"] as! JSONObject)["high"] as! JSONObject)["url"]
                        youVideoDict["videoID"] = (items[i]["id"] as! JSONObject)["videoId"]






                        dataArray.append(youVideoDict)


                       print(dataArray)



                        // video like can get by videoID.




                    }


                }

                catch {
                    print("json error: \(error)")
                }

            }
        }
        task.resume()









}
Hitesh Chauhan
  • 1,520
  • 15
  • 16
0

Its pretty simple to use. You can use it from javascript, there is a simple module in npmjs: https://www.npmjs.com/package/youtube-api-es6

And, its reference I found on its web: https://www.gyanblog.com/gyan/44-youtube-api-nodejs-usage-example

Gorav Singal
  • 508
  • 3
  • 11