我正在使用YouTube API为我的YouTube频道创建应用。我通过以下方式使用Alamofire从播放列表中获取视频:
catch
我一直在寻找,我找不到一个简单的方法来做到这一点。我找到了这样一个答案:How to get number of video views with YouTube API?但是,我正在使用Swift。有没有人有任何想法?
答案 0 :(得分:0)
工作解决方案。我使用Decodable
而不是原始JSON,但我按照您的代码进行了上一次请求。
let apiKey = "API_KEY"
let playlistId = "PLAYLIST_ID"
let url = URL(string: "https://www.googleapis.com/youtube/v3/playlistItems?playlistId=\(playlistId)&maxResults=25&part=snippet%2CcontentDetails&key=\(apiKey)")!
// Get videos
Alamofire.request(url).responseJSON { (response) in
guard let JSON = response.result.value,
let dictionary = JSON as? [String: Any],
let items = dictionary["items"] as? [AnyObject]
else { return }
let videos: [Video] = items.map {
let videoObj = Video()
videoObj.videoID = $0.value(forKeyPath: "snippet.resourceId.videoId") as! String
videoObj.videoTitle = $0.value(forKeyPath: "snippet.title") as! String
videoObj.videoDescription = $0.value(forKeyPath: "snippet.description") as! String
videoObj.videoThumbnailUrl = $0.value(forKeyPath: "snippet.thumbnails.default.url") as! String
return videoObj
}
let videoIds = videos.map({ $0.videoID }).joined(separator: ",")
let statsUrl = URL(string: "https://www.googleapis.com/youtube/v3/videos?part=statistics&id=\(videoIds)&key=\(apiKey)")!
// Get view count for all videos
Alamofire.request(statsUrl).responseJSON { (response) in
guard let JSON = response.result.value,
let dictionary = JSON as? [String: Any],
let items = dictionary["items"] as? [AnyObject]
else { return }
for i in 0..<items.count {
let views = items[i].value(forKeyPath: "statistics.viewCount") as! String
videos[i].viewCount = Int(views)!
}
print(videos)
}
}