我想弄清楚如何在我的iOS應用程序中使用新的YouTube API(版本3),但我不知道該怎麼做。 我做了很多關於它的研究,但是我發現的是所有舊API的示例和代碼,因此它們無效。 直到現在我明白了,要使用新的API,您必須在Google開發者控制檯中創建一個項目(並且我這麼做了)......但是,然後他們會將您帶到一個包含一些代碼的頁面,但我實際上沒有了解如何使用它。 link to google api page 我需要知道的是如何從YouTube視頻的給定網址中檢索一些信息,我需要的信息是「喜歡」的總數和「視圖」的總數......對於API 2,它非常簡單做到這一點...但現在我真的不知道從哪裏開始... 有沒有人請解釋如何實現這一點,也許一些例子和一些代碼? 我很確定很多人都會從中受益。如何使用YouTube API V3?
回答
您不必使用Google提供的iOS客戶端來提出這些請求。
導航到API Console併爲您的iOS應用程序生成一個新的簡單API訪問鍵。請確保在提供的窗口中輸入您的應用程序的包標識符。或者,您可以創建一個服務器API密鑰,用於通過命令行進行基本請求測試和捲曲。
找到您需要的相關端點。要查找有關視頻的信息,您需要使用Videos.list方法。
首先,設置你的URL。我將以此URL爲例:https://www.youtube.com/watch?v=AKiiekaEHhI
您將要爲part
參數指定一個值。從你的問題,它看起來像你會想在snippet
,contentDetails
,並statistics
值傳遞(雖然喜歡和看法,你真的只需要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中執行此操作。
迅速實施:
// 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的實現:
(該帖子已被編輯,以支持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;
}
這種方法可以用於現場活動。
//斯威夫特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
- 1. 使用YouTube API V3
- 2. 如何使用YouTube的API V3
- 3. Youtube v3 api使用code.google.com/p/google-api-go-client/youtube/v3
- 4. 使用的YouTube API V3
- 5. 使用Youtube v3 Api鍵
- 6. Youtube相關影片使用Youtube V3 API
- 7. 如何使用Youtube Data API v3獲取Youtube頻道訂閱者數量我使用Eclipse Kepler和Youtube Data Api v3一起使用Youtube Data API v3
- 8. Youtube API v3 ipRefererBlocked
- 9. Youtube API v3 Java
- 10. 如何使用YouTube V3(c#)
- 11. 如何使用YouTube v3 API檢索YouTube視頻的標籤?
- 12. 如何使用Jquery和Youtube API V3獲得Youtube評論?
- 13. 如何使用youtube v3 api和C刪除YouTube上的視頻#
- 14. 如何禁用的YouTube API V3評論
- 15. Youtube API v3 Video Author
- 16. Youtube API V3難度
- 17. YouTube API V3 - 403 Forbidden
- 18. Youtube API V3和Etag
- 19. 如何使用youtube API v3使用Java獲取視頻的URL
- 20. 如何使用Google API PHP Client Library和Youtube API V3將視頻上傳到YouTube?
- 21. 在處理中使用Youtube Data API v3
- 22. 頁面令牌使用YouTube API a3 v3
- 23. 使用Youtube v3下載字幕API
- 24. 使用Youtube API v3發生「accessNotConfigured」錯誤
- 25. 無法使用v3訪問YouTube API
- 26. Chrome Ext。使用Youtube API v3的OAuth 2.0
- 27. 如何在youtube-api v3中獲得「transcript」
- 28. 如何從YouTube V3 api檢索URL值?
- 29. 如何指定在YouTube的API V3
- 30. 使用youtube v3 with apikey
嘿!感謝您的回答,我使用Objective C和Xcode編程,明天我會嘗試在我的項目中使用您的信息,並讓您知道... 感謝您的幫助 – Blue
@Blue您應該真的改變您的問題上的標籤。 iOS!= Objective-C,Xcode同時使用Objective-C和Swift。不過,我添加了一個Objective-C實現,並要求對您的問題進行編輯以包含Objective-C標記。 – JAL
@藍色的任何更新或問題?如果您需要任何其他幫助,請告訴我。 – JAL