获取Youtube视频viewCount Youtube API v3/Swift
问题描述:
我试图获取Youtube视频的观看次数。获取Youtube视频viewCount Youtube API v3/Swift
"snippet": {
"publishedAt": datetime,
"channelId": string,
"title": string,
"description": string,
"thumbnails": {
(key): {
"url": string,
"width": unsigned integer,
"height": unsigned integer
}
},
"channelTitle": string,
"tags": [
string
],
"categoryId": string,
"liveBroadcastContent": string,
"defaultAudioLanguage": string
},
"statistics": {
"viewCount": unsigned long,
"likeCount": unsigned long,
"dislikeCount": unsigned long,
"favoriteCount": unsigned long,
"commentCount": unsigned long
这是需要解析的JSON。我发现了一个在线教程与snippet
正确分析,像这样:
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i {
let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>
// let statisticsDict = items[i]["statistics"] as! Dictionary<NSObject, AnyObject>
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<NSObject, AnyObject>()
videoDetailsDict["title"] = snippetDict["title"]
videoDetailsDict["channelTitle"] = snippetDict["channelTitle"]
videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"]
// videoDetailsDict["viewCount"] = statisticsDict["viewCount"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(videoDetailsDict)
你可以在试图通过做某种类型的此分析显示了snippet
得到的统计数据看到我的努力,但我有没有运气,结果对于videoDetailsDict
中的“viewCount”总是为零。
我在做什么错?
答
确保在part
参数添加statistics
如下: https://developers.google.com/apis-explorer/?hl=en_US#p/youtube/v3/youtube.videos.list?part=snippet%252Cstatistics&id=QJYMdGpJQFs&_h=10&
另外,如果你只想要视频计(或任何具体信息),我建议你使用fields
参数做出更小,更明确的回应。
即让刚刚viewCount
与fields=items/statistics(viewCount)
https://developers.google.com/apis-explorer/?hl=en_US#p/youtube/v3/youtube.videos.list?part=snippet%252Cstatistics&id=QJYMdGpJQFs&fields=items%252Fstatistics(viewCount)&_h=5&
你应该开始从字典到词典 –
改变你的字典声明确保'targetURL'包含'在部分statistics' –
'var urlString =“https://www.googleapis.com/youtube/v3/search?part=snippet,statistics&q=\(searchBar.text)&type=video&maxResults=15&key=\(apiKey)”'does not work 。你需要单独做GET吗? –