3

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:

enter image description here

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.

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:

[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?

Thanks

Pangu
  • 3,721
  • 11
  • 53
  • 120

2 Answers2

5

I see you are using playlistItems from your link. This will only grab videos from a playlist.

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.

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.

bastelflp
  • 9,362
  • 7
  • 32
  • 67
DBZ Kai
  • 66
  • 1
  • This URL will give us all "Newest" playlist created , but i want list of "Last video added" , do you have any idea about that ?? – Himanshu jamnani Jun 01 '16 at 15:20
  • it will give the playlist under channel id, but not providing the insight detail of playlist , like i have two playlist in channel and each playlist has 50 videos each in this case how i can get the all playlist information in one call ? – Muhammad Shauket Jan 26 '18 at 03:04
3

This is quite a good tutorial on how to get videos from 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?!)

enter image description here

It uses these two pods you must install:

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

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:

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 :

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:

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:

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:

// 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:

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

Here is the code

https://github.com/benSmith1981/youtubeapp

Ben Smith
  • 521
  • 3
  • 15