2016-02-14 105 views
1

我的问题不是关于从通道中检索视频。我只想获取该频道创建的所有“播放列表”,并检索每个播放列表的缩略图,标题和视频数量。如何使用Swift获取YouTube频道的所有播放列表?

这里有一个YouTube频道,例如:

enter image description here

正如你可以看到,有很多创建的播放列表。

至于现在,我只能得到一个通道的最近上传的视频,在这种情况下,仅仅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?

感谢

回答

5

我看你使用playlistItems从你的链接。这只会抓取播放列表中的视频。

按照this linkon the bottom,当你输入部分为snippet和channelid为UCJKOvdk-nVzDAFR_9MF64sw。然后点击执行不使用OAuth。您将从该channelid获取所有播放列表的json对象。

在请求它表明你:使用该URL

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

,你应该能够抓住它。

+0

此URL将会给我们创造的一切“最新”的播放列表,但我想“最后的视频添加”列表中,你有没有想过这事? –

+0

它会根据频道ID给出播放列表,但不会提供播放列表的洞察细节,就像我在频道中有两个播放列表,每个播放列表都有50个视频,在这种情况下,我怎样才能在一次调用中获得所有播放列表信息? –

2

这是一个关于如何从YouTube获得的视频相当不错的教程: http://www.appcoda.com/youtube-api-ios-tutorial/

我使用函数从YouTube获得的播放列表,但它是遗留代码(你需要设置的遗产真的在你的构建你的目标的设置才能使用)不雨燕3.0(有人可以转换?)

enter image description here

它使用这两个吊舱则必须安装:

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需要playlistID作为作为参数,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是刚才选定的那个)。注册我的自定义单元格(我想自定义的YouTube单元的位)在viewDidLoad中:

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) 

下面是代码

https://github.com/benSmith1981/youtubeapp

+0

好的答案!任何更新Swift 3或4? – Dia

+0

在Swift 3中有类似的答案:https://stackoverflow.com/a/42855463/7205816 – Dia

+0

可以传递playListArray作为参数吗? –

相关问题