如何使用YouTube API V3? [英] How to use YouTube API V3?
问题描述
我正在尝试弄清楚如何在我的iOS应用中使用新的YouTube API(第3版),但我不知道该怎么做。
我做了很多关于它的研究,但我发现的是旧API的所有示例和代码,因此它们无效。
现在我明白为了使用新的API,你必须在Google Developer Console中创建一个项目(我做到了)......但是他们会把你发送到一个包含一些代码的页面但是我真的不明白如何使用它。 链接到Google API页面
我需要知道的是如何从YouTube视频的给定URL中检索一些信息,我需要的信息是喜欢的总数和视图的总数...使用API 2这样做非常简单...但是现在我真的不知道从哪里开始......
是否有人可以通过一些例子和一些代码来解释如何实现这个目标?
我很确定很多人会从中受益。
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.
推荐答案
你没有必要使用Google提供的iOS客户端来提出这类请求。
You don't have to use the iOS client Google provides to make those kinds of request.
-
导航到 API控制台并为您的iOS应用程序生成新的Simple API Access密钥。请务必在提供的窗口中输入应用程序的包标识符。或者,您可以创建一个服务器API密钥,用于测试基本请求和命令行中的curl。
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.
根据需要查找相关端点。要查找有关视频的信息,您需要使用 Videos.list 方法。
Find the relevant endpoint for your needs. To find information about a video, you'll want to use the Videos.list method.
首先,设置你的URL。我将使用此网址作为示例: https://www.youtube.com/watch?v = AKiiekaEHhI
First, set up you URL. I will be using this URL as an example: https://www.youtube.com/watch?v=AKiiekaEHhI
您将要为部分
参数指定一个值。从您的问题来看,您似乎想要传递代码段
, contentDetails
和 statistics
值(虽然对于喜欢和观看,你真的只需要 statistics
值)。
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).
然后传入你视频的 id
(在这种情况下 AKiiekaEHhI
,你可以添加最多50个以逗号分隔的ID)和您的API密钥。您的网址应如下所示:
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}
你可以也可以在 API Explorer 中执行此操作。
You can also do this in the API Explorer.
快速实施:
// 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实现:
Objective-C implementation:
(此帖子已被编辑为支持 NSURLSession
。对于使用 NSURLConnection
的实现,请检查编辑历史记录)
(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];
您的日志将如下所示:
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
项目的对象
key将是您传递给请求的每个视频ID的信息数组。
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屋!