如何使用 YouTube API V3? [英] How to use YouTube API V3?

查看:32
本文介绍了如何使用 YouTube API V3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何在我的 iOS 应用中使用新的 YouTube API(版本 3),但我不知道该怎么做.我对此进行了很多研究,但我发现的是旧 API 的所有示例和代码,因此它们无效.直到现在我才明白,要使用新的 API,你必须在谷歌开发者控制台中创建一个项目(我做到了)......但是他们把你带到一个页面上,上面有一些代码,但我真的不明白如何使用它.链接到 google api 页面我需要知道的是如何从 YouTube 视频的给定 URL 中检索一些信息,我需要的信息是喜欢"的总数和视图"的总数......使用 API 2 很简单它......但现在我真的不知道从哪里开始......有没有人可以用一些例子和一些代码来解释如何实现这一点?我很确定很多人都会从中受益.

解决方案

您不必使用 Google 提供的 iOS 客户端来发出此类请求.

  1. 导航到 API 控制台 并为您的iOS 应用程序.请务必在提供的窗口中输入您的应用程序包标识符.或者,您可以创建一个服务器 API 密钥,用于通过命令行测试基本请求和 curl.

  2. 找到满足您需求的相关端点.要查找有关视频的信息,您需要使用 Videos.list 方法.

首先,设置您的网址.我将使用此 URL 作为示例:https://www.youtube.com/watch?v=AKiiekaEHhI

您将要为 part 参数指定一个值.从您的问题来看,您似乎想要传入 snippetcontentDetailsstatistics 值(尽管对于喜欢和意见,你真的只需要 statistics 值).

然后传入您的视频的 id(在本例中为 AKiiekaEHhI,您最多可以添加 50 个逗号分隔的 ID)和您的 API 密钥.您的网址应如下所示:

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

您也可以在 API Explorer 中执行此操作.p>

Swift 实现:

//设置你的 URL让 youtubeApi = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}"让 url = NSURL(字符串:youtubeApi)//创建你的请求let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in做 {如果让 jsonResult = 尝试 NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) 作为?[字符串:任何对象] {print("来自 YouTube 的回复:(jsonResult)")}}抓住 {print("json 错误:(error)")}})//开始请求任务.resume()

Objective-C 实现:

(此帖子已被编辑以支持 NSURLSession.对于使用 NSURLConnection 的实现,请查看编辑历史记录)

//设置你的 URLNSString *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];//创建你的请求NSURLRequest *request = [NSURLRequest requestWithURL:url];//异步发送请求[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {//回调,解析数据并检查错误if (数据 && !connectionError) {NSError *jsonError;NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];如果(!jsonError){NSLog(@"来自 YouTube 的回复:%@", jsonResult);}}}] 恢复];

您的日志将如下所示:

来自 YouTube 的回应:{etag = ""NO6QTeg0-3ShswIeqLchQ_mzWJs/AAjIATmVK_8ySsAWwEuNfdZdjW4"";项目 = ({内容详细信息 = {标题=假;定义=高清;尺寸 = 2d;持续时间 = PT17M30S;许可内容 = 1;};etag = ""NO6QTeg0-3ShswIeqLchQ_mzWJs/8v8ee5uPZQa1-ucVdjBdAVXzcZk"";id = AKiiekaEHhI;kind = "youtube#video";片段 = {类别 ID = 20;频道 ID = UCkvdZX3SVgfDW8ghtP1L2Ug;channelTitle = "无剑链接";description = "在 Twitter 上关注我!http://twitter.com/swordlesslink

在 TwitchTV 上关注我进行视频游戏直播!http://twitch.tv/swordlesslink";直播内容 = 无;本地化 = {description = "在 Twitter 上关注我!http://twitter.com/swordlesslink

在 TwitchTV 上关注我进行视频游戏直播!http://twitch.tv/swordlesslink";title = "塞尔达传说:有故障的马约拉面具 - 第 17 部分:逆流而上";};发布时间=2015-05-04T10:01:43.000Z";缩略图 = {默认 = {高度 = 90;url = "https://i.ytimg.com/vi/AKiiekaEHhI/default.jpg";宽度 = 120;};高 = {高度 = 360;url = "https://i.ytimg.com/vi/AKiiekaEHhI/hqdefault.jpg";宽度 = 480;};中等 = {高度 = 180;url = "https://i.ytimg.com/vi/AKiiekaEHhI/mqdefault.jpg";宽度 = 320;};标准 = {高度 = 480;url = "https://i.ytimg.com/vi/AKiiekaEHhI/sddefault.jpg";宽度 = 640;};};title = "塞尔达传说:有故障的马约拉面具 - 第 17 部分:逆流而上";};统计 = {评论数 = 54;不喜欢计数 = 3;最喜欢计数 = 0;喜欢计数 = 265;视图计数 = 6356;};});kind = "youtube#videoListResponse";页面信息 = {结果每页 = 1;总结果 = 1;};} 错误:无

items 键的对象将是您传递给请求的每个视频 ID 的信息数组.

通过深入研究此响应,您将能够获得所需的信息.例如:

如果让 items = jsonResult["items"] as?[任何对象]?{println(项目?[0][统计"])}

将为您提供视频统计信息的字典(您可以在其中获得喜欢的次数和观看次数).

<代码>{评论数 = 54;不喜欢计数 = 3;最喜欢计数 = 0;喜欢计数 = 265;视图计数 = 6356;}

同样的方法也可以用于现场活动.

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.

解决方案

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

Follow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
                liveBroadcastContent = none;
                localized =                 {
                    description = "Follow me on Twitter! http://twitter.com/swordlesslink

Follow 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.

这篇关于如何使用 YouTube API V3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆