Breaking News
Home / iOS / iOS Snippets / How to use ASIHTTPRequest for Async Http Request?

How to use ASIHTTPRequest for Async Http Request?

What is NSError

As a best practice all the HTTP requests to get some data or perform an operation over the network should be done in an Asynchronous way (separate thread) to avoid the GUI be non-responsive and not freeze  while the http client is waiting for the response from the remote end. This can be accomplished by creating a separate thread and doing the sync request/response there or easily using a library like ASIHTTP that would abstract that for you. <!>

Asychornous Http Request with ASIHTTP

  1. (void) sendAndCallBack: (NSString *) restUrl withCallBack:(NSObject*) delegate
  2. {
  3.     debugLog(@"in :sendAndCallBack");
  4.    
  5.     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: [NSURL URLWithString:restUrl]];
  6.     [request setDelegate: delegate];
  7.     [request setTimeOutSeconds:REQUEST_TIMEOUT];
  8.    
  9.     [request setAllowCompressedResponse:NO];
  10.     [request setDefaultResponseEncoding:NSUTF8StringEncoding];
  11.     [request startAsynchronous];
  12.    
  13.  
  14.      NSError *error = [request error];
  15.      if (!error) {
  16.      NSString *response = [request responseString];
  17.      debugLog(@"Content %@",response);
  18.    
  19.      NSString *contentLength = [[request responseHeaders] objectForKey:@"Content-Length"];
  20.    
  21.    
  22.      for (id key in [request responseHeaders]) {
  23.    
  24.      NSLog(@"key: %@, value: %@", key, [[request responseHeaders] objectForKey:key]);
  25.    
  26.      }
  27.    
  28.      debugLog(@"Content %@",contentLength);
  29.      int cl = [contentLength intValue];
  30.    
  31.  
  32.      int begin = [response length] cl;
  33.      debugLog(@"Content begin %d Length %d",begin ,cl);
  34.    
  35.    
  36.      response = [response substringWithRange:NSMakeRange(begin,  cl)];
  37.    
  38.      debugLog(@"Response %@",response);
  39.      }
  40.    
  41. }
[pb_builder]

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Advertisment ad adsense adlogger