Sharanya K M Sharanya K M - 6 months ago 120
Swift Question

Synchronous fetching data NSOperationQueue or NSURLSession

In my app , we have to make 3 server calls when we click on the login button.

1) will make a server call to get an OAuth token for user credentials
2) with the token from (1) we will get user privileges
3) with the token from (1) and with the valid privilege from (2) we will get the data to be displayed on the page after login in a tableview.

I'm confused with the approach to take for this. Would it be a good approach to use operationqueue adding dependencies or to use NSURLSession tasks ?

According to one of the stack overflow solutions for this - Best practices for making a queue of NSURLSessionTasks ,
NSURLSession does not have any logic about ordering requests it will just call the completionBlock of whatever finishes first even when setting the maximum number of connections per host to 1

If there is any other better approach let me know..


you can use NSURLSession tasks. first call first api method and you will get response in completion handler(block). now store it in any public property (as you want to use it again) within completion handler. From that completion handler call second api method and from the completion handler of that second method, call third api method by passing response and using public property which have first api method's object stored.

Completion handler or blocks getting called only when response is arrived so by this way you can manage your api calls.

Hope this will help :)