multiple Alamofire requests

2019-03-07 02:12发布

问题:

I'm building an app that will list all of a user instagram followers. Instagram API returns only around 50 followers as JSON array and a link to the next 50 and so on till all the followers are sent. This method is called pagination.

What I'm trying to do is the following

  1. Start a request with the a main API URl
  2. append all the sent data to a JSON array
  3. Re-Send a request but with URL set as the pagination URL( that will list the next 50 followers)
  4. append the new sent followers to the JSON array
  5. Keep on doing so until the url for the next 50 is empty ( no more followers)

I'm using Swift 1.2 , Xcode 6.4, Alamofire lastest release, SwiftyJSON latest Release

Here is the code i used

do {

Alamofire.request(.GET, dataURL).responseJSON { (request, response, json, error) in

    print("Request Started")

    if json == nil || error != nil {



        let alertView = UIAlertController(title: "Error", message: "No Data found. Check your internet connection", preferredStyle: .Alert)
        alertView.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil))
        self.presentViewController(alertView, animated: true, completion: nil)
        return
    }else{

        var jsonObject = JSON(json!)

        var dataOfNextURl = jsonObject["pagination"]["next_url"].string!
        print(" Data for next url :\(dataOfNextURl)")
        dataURL = dataOfNextURl



    }




}
}while(dataURL != "")

In the console I'm getting endless "Request Started " printed ( infinite loop, not initiating the request and waiting for the response), but I'm not getting an of the print(" Data for next url :(dataOfNextURl)") executed. I'm guessing that Alamofire is designed to work on a different thread for reducing complexity but if i issue a request alone without the while loop it works as supposed( waits for response before executing later code.


So how can I do this? make alamofire wait for every response before iterating the loop. Thanks

回答1:

NSUserDefaults has a registerDefaults: method for this purpose. Use it (in application:didFinishLaunchingWithOptions:).



回答2:

As matt said, registerDefaults was created for this purpose.

However, if you don't want to use registerDefaults, then I'd suggest using integerForKey and setInteger instead of using objectForKey. integerForKey defaults to 0. So if you use it, the HighScore will default to 0 until it is set.