如何使用 YouTube API V3?
How to use YouTube API V3?
我想知道如何在我的 iOS 应用程序中使用新的 YouTube API(第 3 版),但我不知道该怎么做。
我对此做了很多研究,但我发现的是旧 API 的所有示例和代码,因此它们无效。
直到现在我才明白,要使用新的 API 你必须在 Google 开发者控制台中创建一个项目(我做到了)......但是他们会把你带到一个页面上有一些代码它,但我真的不明白如何使用它。 link to google api page
我需要知道的是如何从 YouTube 视频的给定 URL 中检索一些信息,我需要的信息是 "likes" 的总数和 "views" 的总数...... API 2 做起来很简单...但现在我真的不知道从哪里开始...
是否有人可以通过一些示例和一些代码来解释如何实现这一目标?
我很确定很多人会从中受益。
您不必使用 iOS 客户端 Google 提供这些类型的请求。
导航到 API Console 并为您的 iOS 应用程序生成一个新的简单 API 访问密钥。请务必在提供的 window 中输入您应用的捆绑包标识符。或者,您可以创建一个服务器 API 密钥,用于使用基本请求进行测试,并从命令行卷曲。
找到满足您需求的相关端点。要查找有关视频的信息,您需要使用 Videos.list 方法。
首先,设置你 URL。我将使用此 URL 作为示例:https://www.youtube.com/watch?v=AKiiekaEHhI
您需要为 part
参数指定一个值。从您的问题来看,您似乎想要传递 snippet
、contentDetails
和 statistics
值(尽管对于点赞和观看,您实际上只需要 statistics
值).
然后传入您视频的 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}
您也可以在 API Explorer 中执行此操作。
Swift 实施:
// 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 实施:
(已编辑此 post 以支持 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];
您的日志将如下所示:
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
items
键的对象将是您传入请求的每个视频 ID 的信息数组。
通过深入研究此回复,您将能够获得所需的信息。例如:
if let items = jsonResult["items"] as? [AnyObject]? {
println(items?[0]["statistics"])
}
会给你一个视频统计数据的字典(你可以从中得到喜欢的次数和观看次数)。
{
commentCount = 54;
dislikeCount = 3;
favoriteCount = 0;
likeCount = 265;
viewCount = 6356;
}
同样的方法可以用于现场活动。
// 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®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()
}
使用起来非常简单。
你可以从javascript开始使用它,npmjs中有一个简单的模块:https://www.npmjs.com/package/youtube-api-es6
而且,我在其网站上找到的参考文献:https://www.gyanblog.com/gyan/44-youtube-api-nodejs-usage-example
我想知道如何在我的 iOS 应用程序中使用新的 YouTube API(第 3 版),但我不知道该怎么做。 我对此做了很多研究,但我发现的是旧 API 的所有示例和代码,因此它们无效。 直到现在我才明白,要使用新的 API 你必须在 Google 开发者控制台中创建一个项目(我做到了)......但是他们会把你带到一个页面上有一些代码它,但我真的不明白如何使用它。 link to google api page 我需要知道的是如何从 YouTube 视频的给定 URL 中检索一些信息,我需要的信息是 "likes" 的总数和 "views" 的总数...... API 2 做起来很简单...但现在我真的不知道从哪里开始... 是否有人可以通过一些示例和一些代码来解释如何实现这一目标? 我很确定很多人会从中受益。
您不必使用 iOS 客户端 Google 提供这些类型的请求。
导航到 API Console 并为您的 iOS 应用程序生成一个新的简单 API 访问密钥。请务必在提供的 window 中输入您应用的捆绑包标识符。或者,您可以创建一个服务器 API 密钥,用于使用基本请求进行测试,并从命令行卷曲。
找到满足您需求的相关端点。要查找有关视频的信息,您需要使用 Videos.list 方法。
首先,设置你 URL。我将使用此 URL 作为示例:https://www.youtube.com/watch?v=AKiiekaEHhI
您需要为 part
参数指定一个值。从您的问题来看,您似乎想要传递 snippet
、contentDetails
和 statistics
值(尽管对于点赞和观看,您实际上只需要 statistics
值).
然后传入您视频的 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}
您也可以在 API Explorer 中执行此操作。
Swift 实施:
// 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 实施:
(已编辑此 post 以支持 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];
您的日志将如下所示:
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
items
键的对象将是您传入请求的每个视频 ID 的信息数组。
通过深入研究此回复,您将能够获得所需的信息。例如:
if let items = jsonResult["items"] as? [AnyObject]? {
println(items?[0]["statistics"])
}
会给你一个视频统计数据的字典(你可以从中得到喜欢的次数和观看次数)。
{
commentCount = 54;
dislikeCount = 3;
favoriteCount = 0;
likeCount = 265;
viewCount = 6356;
}
同样的方法可以用于现场活动。
// 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®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()
}
使用起来非常简单。 你可以从javascript开始使用它,npmjs中有一个简单的模块:https://www.npmjs.com/package/youtube-api-es6
而且,我在其网站上找到的参考文献:https://www.gyanblog.com/gyan/44-youtube-api-nodejs-usage-example