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.
我想弄清楚如何在我的iOS应用程序中使用新的YouTube API(版本3),但我不知道如何使用。我做了很多研究,但是我发现所有的例子和代码都是旧的API,所以它们是无效的。直到现在我才明白,要使用新的API,你必须在谷歌开发人员控制台(我做到了)创建一个项目……但是他们把你送到一个上面有一些代码的页面,但是我真的不明白如何使用它。链接到谷歌api页面我需要知道的是如何从一个YouTube视频的给定URL中检索一些信息,我需要的信息是“喜欢”的总数和“观看”的总数……使用API 2,它很简单…但是现在我真的不知道从哪里开始……是否有人可以通过一些例子和代码来解释如何实现这个目标?我相信很多人都会从中受益。
3 个解决方案
#1
19
You don't have to use the iOS client Google provides to make those kinds of request.
您不必使用iosclient谷歌提供的来发出这些请求。
-
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.
导航到API控制台并为iOS应用程序生成一个新的简单的API访问键。确保在提供的窗口中输入应用程序的包标识符。或者,您可以创建一个服务器API密钥,用于使用基本请求和命令行中的curl测试。
-
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
首先,设置URL。我将使用这个URL作为示例:https://www.youtube.com/watch?
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).
您将需要为部件参数指定一个值。从您的问题来看,您似乎希望传递代码片段、内容细节和统计值(尽管对于like和视图,您确实只需要统计值)。
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 :
然后传入视频的id(在本例中为AKiiekaEHhI,您可以添加多达50个逗号分隔的id)和API密钥。你的URL应该是这样的:
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.
在API资源管理器中也可以这样做。
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:
objective - c实现:
(This post has been edited to support NSURLSession
. For an implementation that uses NSURLConnection
, check the edit history)
(本文经过编辑以支持NSURLSession。对于使用NSURLConnection的实现,请检查编辑历史)
// 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.
items key的对象将是你传递给请求的每个视频id的一个信息数组。
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.
这种方法也可以用于实时事件。
#2
4
// Swift 3
/ /斯威夫特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®ionCode=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()
}
#3
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
使用起来很简单。可以从javascript使用它,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
我在它的web上找到了它的引用:https://www.gyanblog.com/gyan/44-youtube-api-nodejs- use -example
#1
19
You don't have to use the iOS client Google provides to make those kinds of request.
您不必使用iosclient谷歌提供的来发出这些请求。
-
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.
导航到API控制台并为iOS应用程序生成一个新的简单的API访问键。确保在提供的窗口中输入应用程序的包标识符。或者,您可以创建一个服务器API密钥,用于使用基本请求和命令行中的curl测试。
-
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
首先,设置URL。我将使用这个URL作为示例:https://www.youtube.com/watch?
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).
您将需要为部件参数指定一个值。从您的问题来看,您似乎希望传递代码片段、内容细节和统计值(尽管对于like和视图,您确实只需要统计值)。
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 :
然后传入视频的id(在本例中为AKiiekaEHhI,您可以添加多达50个逗号分隔的id)和API密钥。你的URL应该是这样的:
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.
在API资源管理器中也可以这样做。
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:
objective - c实现:
(This post has been edited to support NSURLSession
. For an implementation that uses NSURLConnection
, check the edit history)
(本文经过编辑以支持NSURLSession。对于使用NSURLConnection的实现,请检查编辑历史)
// 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.
items key的对象将是你传递给请求的每个视频id的一个信息数组。
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.
这种方法也可以用于实时事件。
#2
4
// Swift 3
/ /斯威夫特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®ionCode=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()
}
#3
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
使用起来很简单。可以从javascript使用它,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
我在它的web上找到了它的引用:https://www.gyanblog.com/gyan/44-youtube-api-nodejs- use -example