my question is not in regards to retrieving videos from a channel in general. I would only like to get all the "playlists" that the channel has created, and retrieve the thumbnail, title, and number of videos of each playlist.
我的问题不在于从一般渠道中检索视频。我只想获得频道创建的所有“播放列表”,并检索每个播放列表的缩略图,标题和视频数量。
Here's a youtube channel example:
这是一个youtube频道示例:
As you can see, there are many created playlists.
如您所见,有许多创建的播放列表。
As of right now, I'm only able to get the most recent uploaded videos of a channels, in this case just 5.
截至目前,我只能获得最新上传的频道视频,在这种情况下只有5个。
Using the following code:
使用以下代码:
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)")
}
})
The output of resultsDict
:
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;
}]
Instead of getting retrieve the channel's videos, how do I retrieve their playlists instead using the youtube api v3?
而不是检索频道的视频,如何使用youtube api v3检索其播放列表?
Thanks
2 个解决方案
#1
5
I see you are using playlistItems
from your link. This will only grab videos from a playlist.
我看到你正在使用链接中的playlistItems。这只会从播放列表中获取视频。
follow this link and on the bottom, when you enter part as snippet
and channelid as UCJKOvdk-nVzDAFR_9MF64sw
. Then click Execute without OAuth. You will get json object of all playlist from that channelid.
当您输入部分作为片段和channelid作为UCJKOvdk-nVzDAFR_9MF64sw时,请点击此链接并在底部。然后单击“执行而不使用OAuth”。您将从该channelid获取所有播放列表的json对象。
In the request it shows you this:
在请求中它显示了这个:
GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCJKOvdk-nVzDAFR_9MF64sw&key={YOUR_API_KEY}
using that url, you should be able to grab it.
使用该网址,您应该能够抓住它。
#2
2
This is quite a good tutorial on how to get videos from youtube: http://www.appcoda.com/youtube-api-ios-tutorial/
这是一个关于如何从youtube上获取视频的相当好的教程:http://www.appcoda.com/youtube-api-ios-tutorial/
I use the function to get playlist from youtube, but it is legacy code(you need to set legacy to true in your build settings of your target to use) not Swift 3.0 (can someone convert?!)
我使用该函数从youtube获取播放列表,但它是遗留代码(您需要在目标的构建设置中将遗留设置为true)而不是Swift 3.0(有人可以转换吗?!)
It uses these two pods you must install:
它使用您必须安装的这两个pod:
pod "youtube-ios-player-helper", "~> 0.1.4"
pod "iOS-GTLYouTube"
Then import them into your view controller: import youtube_ios_player_helper import iOS_GTLYouTube
然后将它们导入视图控制器:import youtube_ios_player_helper import iOS_GTLYouTube
I have a tab bar with several different table views, and I load a different playlist depending on what tab is selected. First I use the protocol YTPlayerViewDelegate in my table view controller definition:
我有一个带有几个不同表视图的标签栏,我根据选择的标签加载不同的播放列表。首先,我在表视图控制器定义中使用协议YTPlayerViewDelegate:
class YouTubeTableViewController: UITableViewController, YTPlayerViewDelegate {
Then I add some properties to my table view controller, get your api key here https://console.developers.google.com/projectselector/apis/credentials :
然后我将一些属性添加到我的表视图控制器,在这里获取您的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>> = []
I then use these to functions, getVideosForPlayList requires a playlistID as as parameter, performGetRequest performs the request to youtube to get the playlist videos:
然后我使用这些函数,getVideosForPlayList需要一个播放列表ID作为参数,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()
}
I call the getVideosForPlaylist function from my viewDidAppear function (so a different list is loaded each time, and the selectedIndex of the tabbar is the one just selected). I register my custom cell (I want to customize my youtube cell a bit) in viewDidLoad:
我从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)
}
}
In my number of rows in section table view method I make sure I return the number of videos in my videosArray, that changes depending on the channel you load of course:
在我的部分表视图方法的行数中,我确保返回videosArray中的视频数量,这会根据您加载的频道而变化:
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videosArray.count
}
In my cellForRowAtIndexPath function I make sure I get the correct video ID for each video loaded and pass this videoID into my loadVideoWithID function:
在我的cellForRowAtIndexPath函数中,我确保为每个加载的视频获取正确的视频ID,并将此videoID传递给我的loadVideoWithID函数:
let video = videosArray[indexPath.row]
let videoID = video["videoID"] as! String
cell.youTubePlayer.loadWithVideoId(videoID)
Here is the code
这是代码
#1
5
I see you are using playlistItems
from your link. This will only grab videos from a playlist.
我看到你正在使用链接中的playlistItems。这只会从播放列表中获取视频。
follow this link and on the bottom, when you enter part as snippet
and channelid as UCJKOvdk-nVzDAFR_9MF64sw
. Then click Execute without OAuth. You will get json object of all playlist from that channelid.
当您输入部分作为片段和channelid作为UCJKOvdk-nVzDAFR_9MF64sw时,请点击此链接并在底部。然后单击“执行而不使用OAuth”。您将从该channelid获取所有播放列表的json对象。
In the request it shows you this:
在请求中它显示了这个:
GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCJKOvdk-nVzDAFR_9MF64sw&key={YOUR_API_KEY}
using that url, you should be able to grab it.
使用该网址,您应该能够抓住它。
#2
2
This is quite a good tutorial on how to get videos from youtube: http://www.appcoda.com/youtube-api-ios-tutorial/
这是一个关于如何从youtube上获取视频的相当好的教程:http://www.appcoda.com/youtube-api-ios-tutorial/
I use the function to get playlist from youtube, but it is legacy code(you need to set legacy to true in your build settings of your target to use) not Swift 3.0 (can someone convert?!)
我使用该函数从youtube获取播放列表,但它是遗留代码(您需要在目标的构建设置中将遗留设置为true)而不是Swift 3.0(有人可以转换吗?!)
It uses these two pods you must install:
它使用您必须安装的这两个pod:
pod "youtube-ios-player-helper", "~> 0.1.4"
pod "iOS-GTLYouTube"
Then import them into your view controller: import youtube_ios_player_helper import iOS_GTLYouTube
然后将它们导入视图控制器:import youtube_ios_player_helper import iOS_GTLYouTube
I have a tab bar with several different table views, and I load a different playlist depending on what tab is selected. First I use the protocol YTPlayerViewDelegate in my table view controller definition:
我有一个带有几个不同表视图的标签栏,我根据选择的标签加载不同的播放列表。首先,我在表视图控制器定义中使用协议YTPlayerViewDelegate:
class YouTubeTableViewController: UITableViewController, YTPlayerViewDelegate {
Then I add some properties to my table view controller, get your api key here https://console.developers.google.com/projectselector/apis/credentials :
然后我将一些属性添加到我的表视图控制器,在这里获取您的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>> = []
I then use these to functions, getVideosForPlayList requires a playlistID as as parameter, performGetRequest performs the request to youtube to get the playlist videos:
然后我使用这些函数,getVideosForPlayList需要一个播放列表ID作为参数,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()
}
I call the getVideosForPlaylist function from my viewDidAppear function (so a different list is loaded each time, and the selectedIndex of the tabbar is the one just selected). I register my custom cell (I want to customize my youtube cell a bit) in viewDidLoad:
我从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)
}
}
In my number of rows in section table view method I make sure I return the number of videos in my videosArray, that changes depending on the channel you load of course:
在我的部分表视图方法的行数中,我确保返回videosArray中的视频数量,这会根据您加载的频道而变化:
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videosArray.count
}
In my cellForRowAtIndexPath function I make sure I get the correct video ID for each video loaded and pass this videoID into my loadVideoWithID function:
在我的cellForRowAtIndexPath函数中,我确保为每个加载的视频获取正确的视频ID,并将此videoID传递给我的loadVideoWithID函数:
let video = videosArray[indexPath.row]
let videoID = video["videoID"] as! String
cell.youTubePlayer.loadWithVideoId(videoID)
Here is the code
这是代码