如何使用Swift获取YouTube频道的所有播放列表?

我的问题不是关于从通道中检索video。 我只想获取该频道创build的所有“播放列表”,并检索每个播放列表的缩略图,标题和video数量。

以下是YouTube频道示例:

在这里输入图像说明

正如你所看到的,有很多创build的播放列表。

截至目前,我只能获取最近上传的频道video,在这种情况下只有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来获取频道的video?

谢谢

我看到你正在使用您的链接playlistItems 。 这只会抓取播放列表中的video。

按照这个链接和底部 ,当你input部分作为snippet和channelid UCJKOvdk-nVzDAFR_9MF64sw 。 然后点击执行不使用OAuth。 您将从该channelid获取所有播放列表的json对象。

在请求显示你这个:

 GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCJKOvdk-nVzDAFR_9MF64sw&key={YOUR_API_KEY} 

使用该url,你应该能够抓住它。

这是一个很好的教程,如何从YouTube上获取video: http : //www.appcoda.com/youtube-api-ios-tutorial/

我使用该function从YouTube获取播放列表,但它是遗留代码(您需要将您的目标的生成设置中的遗产设置为真使用)而不是Swift 3.0(可以有人转换?!)

在这里输入图像说明

它使用您必须安装的这两个窗格:

 pod "youtube-ios-player-helper", "~> 0.1.4" pod "iOS-GTLYouTube" 

然后将它们导入到您的视图控制器:导入youtube_ios_player_helper导入iOS_GTLYouTube

我有一个标签栏与几个不同的表视图,我加载一个不同的播放列表取决于select哪个标签。 首先我在我的表视图控制器定义中使用协议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>> = [] 

然后,我使用这些function,获取VideosForPlayList需要一个播放列表ID作为参数,performGetRequest执行请求,以youtube获取播放列表video:

 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是刚才select的那个)。 我在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) } } 

在我在表格视图方法中的行数中,确保我返回video数组中的video数量,这取决于您加载的频道。

 // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return videosArray.count } 

在我的cellForRowAtIndexPath函数中,我确保为每个加载的video获得正确的videoID,并将此videoID传递到我的loadVideoWithID函数中:

 let video = videosArray[indexPath.row] let videoID = video["videoID"] as! String cell.youTubePlayer.loadWithVideoId(videoID) 

这是代码

https://github.com/benSmith1981/youtubeapp