我的问题不在于从一般渠道中检索视频。我只想获得频道创建的所有“播放列表”,并检索每个播放列表的缩略图,标题和视频数量。
这是一个YouTube频道示例:
如您所见,有许多创建的播放列表。
截至目前,我只能获取最新上传的频道视频,在这种情况下只有5个。
使用以下代码:
let urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(playlistID)&key=\(apiKey)"
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Fetch the playlist from Google.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil
{
// Convert the JSON data into a dictionary.
let resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! Dictionary<NSObject, AnyObject>
print("resultsDict = \(resultsDict)")
......
}
else
{
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel videos: \(error)")
}
})
resultsDict
的输出:
[etag: "DsOZ7qVJA4mxdTxZeNzis6uE6ck/0JswUeQp5Wp8607mWPWAfIZaNnM", kind: youtube#playlistItemListResponse, items: (
{
etag = "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/hQUAFFn45u2V47VqvBg1urbZevU\"";
id = "UUS8cX3kg_pL2jw7cOjGoiBw9Ri_jF-DJp";
kind = "youtube#playlistItem";
snippet = {
channelId = "UCJKOvdk-nVzDAFR_9MF64sw";
channelTitle = AppSpy;
description = "James (@Metal_Slag) punches blocks and butt-stomps critters in neon platformer Super Phantom Cat.\n\nDOWNLOAD FROM THE APP STORE:\nhttps://itunes.apple.com/us/app/super-phantom-cat-be-jumpin/id1041873285?mt=8\n\nSUBSCRIBE TO APPSPY:\nhttps://www.youtube.com/subscription_center?add_user=appspy\n\nVISIT:\nhttp://www.pocketgamer.co.uk";
playlistId = "UUJKOvdk-nVzDAFR_9MF64sw";
position = 0;
publishedAt = "2016-02-12T15:59:10.000Z";
resourceId = {
kind = "youtube#video";
videoId = qkMOjc02NRg;
};
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/qkMOjc02NRg/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/qkMOjc02NRg/hqdefault.jpg";
width = 480;
};
maxres = {
height = 720;
url = "https://i.ytimg.com/vi/qkMOjc02NRg/maxresdefault.jpg";
width = 1280;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/qkMOjc02NRg/mqdefault.jpg";
width = 320;
};
standard = {
height = 480;
url = "https://i.ytimg.com/vi/qkMOjc02NRg/sddefault.jpg";
width = 640;
};
};
title = "MEW-RIO? | Super Phantom Cat iPhone & iPad Preview";
};
},
....
// Display info for most recent remaining 4 videos
....
, nextPageToken: CAUQAA, pageInfo: {
resultsPerPage = 5;
totalResults = 3966;
}]
如何使用youtube api v3检索其播放列表,而不是检索频道的视频?
由于
答案 0 :(得分:5)
我发现您正在使用链接中的playlistItems
。这只会从播放列表中抓取视频。
snippet
且channelid为UCJKOvdk-nVzDAFR_9MF64sw
时,请按<{3}}和this link。然后单击“执行而不使用OAuth”。您将从该channelid获取所有播放列表的json对象。
在请求中,它会向您显示:
GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCJKOvdk-nVzDAFR_9MF64sw&key={YOUR_API_KEY}
使用该网址,您应该可以抓住它。
答案 1 :(得分:2)
这是一个非常好的教程,介绍如何从youtube获取视频: http://www.appcoda.com/youtube-api-ios-tutorial/
我使用该函数从youtube获取播放列表,但它是遗留代码(您需要在目标的构建设置中将遗留设置为true)而不是Swift 3.0(有人可以转换吗?!)
它使用您必须安装的这两个pod:
pod "youtube-ios-player-helper", "~> 0.1.4"
pod "iOS-GTLYouTube"
然后将它们导入视图控制器: 导入youtube_ios_player_helper 导入iOS_GTLYouTube
我有一个带有几个不同表视图的标签栏,我根据选择的标签加载不同的播放列表。首先,我在表视图控制器定义中使用协议YTPlayerViewDelegate:
class YouTubeTableViewController: UITableViewController, YTPlayerViewDelegate {
然后我向表视图控制器添加一些属性,在这里获取api密钥https://console.developers.google.com/projectselector/apis/credentials:
var apiKey = "" //place your api key here, get your API key from https://console.developers.google.com/projectselector/apis/credentials
//PLVirhGJQqidpY7n9PJ57FwaW1iogJsFZH = Photographer
//PLVirhGJQqidqjbXhirvXnLZ5aLzpHc0lX = workout
//This array holds all the playlist ID's
var playListArray = ["PLVirhGJQqidpY7n9PJ57FwaW1iogJsFZH","PLVirhGJQqidqjbXhirvXnLZ5aLzpHc0lX"]
//An array to store the videos in your playlist
var videosArray: Array<Dictionary<NSObject, AnyObject>> = []
然后我使用这些函数,getVideosForPlayList需要播放列表作为参数,performGetRequest执行请求到youtube获取播放列表视频:
func getVideosForPlayList(playListID: String) {
// Get the selected channel's playlistID value from the channelsDataArray array and use it for fetching the proper video playlst.
let playlistID = playListID
// Form the request URL string.
let urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(playlistID)&key=\(apiKey)"
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Fetch the playlist from Google.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
do {
// Convert the JSON data into a dictionary.
let resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! Dictionary<NSObject, AnyObject>
// Get all playlist items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
// Use a loop to go through all video items.
for var i=0; i<items.count; ++i {
let playlistSnippetDict = (items[i] as Dictionary<NSObject, AnyObject>)["snippet"] as! Dictionary<NSObject, AnyObject>
// Initialize a new dictionary and store the data of interest.
var desiredPlaylistItemDataDict = Dictionary<NSObject, AnyObject>()
desiredPlaylistItemDataDict["title"] = playlistSnippetDict["title"]
desiredPlaylistItemDataDict["thumbnail"] = ((playlistSnippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
desiredPlaylistItemDataDict["videoID"] = (playlistSnippetDict["resourceId"] as! Dictionary<NSObject, AnyObject>)["videoId"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(desiredPlaylistItemDataDict)
// Reload the tableview.
}
self.tableView.reloadData()
} catch {
print(error)
}
}
else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel videos: \(error)")
}
})
}
// MARK: Custom method implementation
func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
let request = NSMutableURLRequest(URL: targetURL)
request.HTTPMethod = "GET"
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration)
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
})
})
task.resume()
}
我从viewDidAppear函数中调用getVideosForPlaylist函数(因此每次都会加载一个不同的列表,并且tabbar的selectedIndex是刚刚选中的列表)。我在viewDidLoad中注册我的自定义单元格(我想稍微自定义我的youtube单元格):
override func viewDidLoad() {
super.viewDidLoad()
let youTubeCell = UINib(nibName: "YouTubeCell", bundle: nil)
self.tableView.registerNib(youTubeCell, forCellReuseIdentifier: "YouTubeCell")
}
override func viewDidAppear(animated: Bool) {
self.videosArray = []
if let tabIndex = self.tabBarController?.selectedIndex,
let playListID = playListArray[tabIndex] as? String{
getVideosForPlayList(playListID)
}
}
在我的部分表格视图方法中的行数中,我确保返回我的videosArray中的视频数量,这些视频会根据您加载的频道而变化:
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videosArray.count
}
在我的cellForRowAtIndexPath函数中,我确保为每个加载的视频获取正确的视频ID,并将此videoID传递给我的loadVideoWithID函数:
let video = videosArray[indexPath.row]
let videoID = video["videoID"] as! String
cell.youTubePlayer.loadWithVideoId(videoID)
这是代码