我正在使用YouTube应用程序接口为我的YouTube频道创建一个应用程序。我正在使用Alamofire从一个播放列表中获取视频,方法如下:
let parameters = ["part":"snippet","maxResults":50,"channelId":CHANNEL_ID,"playlistId":UPLOADS_PLAYLIST_ID,"key":API_KEY] as [String : Any]
class VideoModel: NSObject {
var videoArray = [Video]()
func getFeedVideo() {
Alamofire.request("https://www.googleapis.com/youtube/v3/playlistItems", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let JSON = response.result.value {
if let dictionary = JSON as? [String: Any] {
var arrayOfVideos = [Video]()
guard let items = dictionary["items"] as? NSArray else { return }
for items in dictionary["items"] as! NSArray {
print(items)
// Create video objects off of the JSON response
let videoObj = Video()
videoObj.videoID = (items as AnyObject).value(forKeyPath: "snippet.resourceId.videoId") as! String
videoObj.videoTitle = (items as AnyObject).value(forKeyPath: "snippet.title") as! String
videoObj.videoDescription = (items as AnyObject).value(forKeyPath: "snippet.description") as! String
videoObj.videoThumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
}我一直在寻找,但我找不到一种简单的方法来做到这一点。我找到了一个类似这样的答案:How to get number of video views with YouTube API?,但是,我使用的是Swift。有谁有什么想法吗?
发布于 2017-08-04 22:48:40
有效的解决方案。我使用的是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)
}
}https://stackoverflow.com/questions/45496510
复制相似问题