0

I'm fetching videos from Youtube channel, I'm able to display 10 videos when APP is starting.

I would like to use the following trick (using pagetoken ; Retrieve all videos from youtube playlist using youtube v3 API) to display more videos.

The idea is to scroll down to fetch the next videos, by using willDisplayCell method.

ViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    self.model.delegate = self
    model.getFeedVideo()

    self.tableView.dataSource = self
    self.tableView.delegate = self
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if !loadingData && indexPath.row == 10 - 1 {
        model.getFeedVideo()
        print("loading more ...")
    }
}
  1. How to use pageToken from ViewController whereas I get the token from VideoModel class?
  2. How to automatically increment the "10" for indexPath attribute? Is it possible to get the current number of displayed cell?

VideoModel:

protocol VideoModelDelegate {
    func dataReady()
}

class VideoModel: NSObject {

func getFeedVideo() {

    var nextToken:String
    nextToken = "XXXXXX"

    // Fetch the videos dynamically via the Youtube Data API
    Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/playlistItems", parameters: ["part":"snippet", "playlistId":PLAYLIST_ID, "key":API_KEY, "maxResults":10, "pageToken":nextToken], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) -> Void in

        if let JSON = response.result.value {

            nextToken = JSON["nextPageToken"] as! String
            print(nextToken)

            var arrayOfVideos = [Video]()

            for video in JSON["items"] as! NSArray {
                // Creating video object...
                // Removed to make it clearer
            }

            self.videoArray = arrayOfVideos

            if self.delegate != nil {
                self.delegate?.dataReady()
            }

        }
    }
}
  1. Do I need to add a return value or should I create another method to get the pageToken? Please, suggest.
Community
  • 1
  • 1
remjih
  • 313
  • 1
  • 9

1 Answers1

0

I will give you a general idea on how to accomplish it.

First: Check if user has scrolled to the last element with if !loadingData && indexPath.row == self.videos.count - 1

Second(edit):

//VideoModel.swift

if self.delegate != nil {
//Pass fetched videos and token to the delegate method.
    self.delegate?.dataReady(self.videoArray, nextToken)
}

Now, few changes in delegate method:

//ViewController.swift

func dataReady(Array->Videos,String->Token) {
   //Define a variable globally and assign received token for later use
   tokenGlobal = Token

  //add received array of videos to the current array of videos

    [self.videos addObjectsFromArray:Videos];

  //Here are two options to populate new videos,

    //First, Reload whole table view, not a recommended approach, since it will take much more time to load

    self.tableView.reloadData()

   //Second, add cells to the existing tableView, instead of loading whole table it will added new cells according to the newly added videos into the array.
}

Now when user reaches the end of tableView, pass the token we have saved in global variable like this:

if !loadingData && indexPath.row == self.videos - 1 {
    model.getFeedVideo(tokenGlobal)
    print("loading more ...")
}

Now, use this tokenGlobal to fetch more videos using 'getFeedVideo' Method.

Look for SO to find out how to add new cells to table view. But for testing you can proceed with reloadData.

P.S: I don't know the Swift syntax. :)

Bista
  • 7,869
  • 3
  • 27
  • 55
  • 1/ videoArray isn't available from ViewController. I'll try to deal with model.videoArray or something else :) 2/ The token provided by Youtube is related to pagination (each page contains 10 videos, in my example). The problem is: I cannot pass the token directly to the getFeedVideo method because I collect the token inside it... What do you think about returning this token? It doesn't look elegant :P – remjih Dec 29 '15 at 10:58
  • Okay..you mean to say that Alamofire is returning nextToken within the success block? – Bista Dec 29 '15 at 11:03
  • 1
    Yes (https://developers.google.com/youtube/v3/docs/playlistItems/list#response), Youtube API return me next / prev token. As I do the request through Alamofire, yes, it returns me the token with other datas (videos list). – remjih Dec 29 '15 at 11:17