kodeshpa
kodeshpa

Reputation: 549

Right way to implement HTTP post / Get in iOS

I am quite new to iOS, trying best way to implement HTTP post / Get communication.

Problem:

I want to make a multiple api calls and each calls will have its separate response. I am trying to write common network utils, Ideally it will take api url, make call and return data to caller. What is the right way to achive it?? I found moderate level of debate and fans for each approach.

Option 1:

 dispatch_async(aQueue,^{
    ...[ make a sync network request get data back]
    --- perform operation on data 
   --- then pass proceed data UI or set it in model. 

   dispatch_async(dispatch_get_main_queue()
  }

Option 2:

 -(NSString *) postData:(NSDictionary *)data serverUrl:(NSString *)targetUrl
   -- call post data method with seperate delegate for each caller 
   -- start async request 
   -- on DidFinishedLaunching or OnError check delegate & then 
      return response back to callback 

Thanks for your inputs.

Upvotes: 1

Views: 371

Answers (2)

bibo bode
bibo bode

Reputation: 1150

There is a wonderful library available, called AFNetworking, which is very easy to implement.

It uses blocks, which greatly simply communication of data between classes (does away with delegates), and is asynchronous.

Example usage is below:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:"www.yourwebsite.com/api"]];

NSDictionary *params = @{
    @"position": [NSString stringWithFormat:@"%g", position]
};

[client postPath:@"/api" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

As simple as that! Result is available directly within the class that calls the HTTP Post or Get method.

It even includes image and JSON requests, JSON deserialization, file download with progress callback, and so much more.

Upvotes: 1

Siby
Siby

Reputation: 318

I think your first option is not good. It is going to block the pooled thread for a long period of time which is not advisable. When implementing Multithreading in any environment pooled threads provided by the system should not be used for long running processes. Second synchronus network call are not really advised and it has its own pitfalls.

Your second option is more viable. An improvement that you may be able to do is to perform the work that happens in the did finish launching to a GCD thread and after the processing send the data on the main thread

Upvotes: 1

Related Questions