Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Network Programming with Swift 2 Protocol Oriented Networking Defining the Fetch Method

Fetching JSON with token "next_page" ?

Hi everyone! I've been working in network requests with the help of Treehouse. I tried to modify the code to fetch another JSON if there's a next_page_token in the previous JSON. I've added some lines in the fetch method by checking whether if there's "next_page_token" keyword in the "parse" closure. If yes, it will recall (recursion?) the fetch method. However I've been keep getting "Invalid Request". Does anyone knows how to deal with this problem? Or there's another better algorithm for fetching next page?

I used the same logic you explained in a project and it did work for me.. did you make sure the url you are passing in the recall (recursion) is the one you read from the next page token ? I assume yes. could you share the code including the parse closure, I could have a look.

This is the modified one: func updateList(coordinate: Coordinate, nextPage: String?, completion: @escaping (APIResult<Restaurant>) -> Void) { var request: URLRequest if let nextPageToken = nextPage { request = Restaurants.NextPage(token: self.token, nextPageToken: nextPageToken).request }else { request = Restaurants.Current(token: self.token, coordinate: coordinate).request } var restaurants: [Restaurant] = [] fetch(request: request as NSURLRequest, parse: {json -> [Restaurant]? in

        if let lists = self.fetchList(json: json) {
            print(json)
            restaurants.append(contentsOf: lists)
            print("Appending new items: \(lists.count)")
            // In case there's next page
            if let nextPageToken = json["next_page_token"] as? String {
                self.updateList(coordinate: coordinate, nextPage: nextPageToken, completion: completion)
            } 
            return restaurants
        } else {
            return nil
        }
    }, completion: completion)

}

The code looks good, did you try to add a breakpoints on the line recalling the function and check the values being passed? only one comment I have, that var restaurants: [Restaurant] = [] will always be empty each time the function calls itself. so please consider to define it at class/struct level as class variable so it holds the previously loaded values on the next call. It wont be captured by the closure!