我试图获取Youtube视频的观看次数。
"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
这里显示的某种类型的解析来看到我试图获取统计数据的尝试但是我没有运气,结果总是为#34; viewCount&#34;在videoDetailsDict
。
我做错了什么?
答案 0 :(得分:0)
确保在statistics
参数中添加part
,如下所示:
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&