How to make asynchronous HTTP requests with NSURLConnection

Objective-C posted almost 4 years ago by christian

Example of how to make asynchronous HTTP requests with NSURLConnection:

   1  //
   2  //  HTTP.h
   3  //
   4  #import <Cocoa/Cocoa.h>
   5  #import "HTTPDelegate.h"
   6  
   7  @interface HTTP : NSObject {
   8  	id delegate;
   9  	NSMutableData *receivedData;
  10  	NSURL *url;
  11  }
  12  @property (nonatomic,retain) NSMutableData *receivedData;
  13  @property (retain) id delegate;
  14  
  15  - (void)get: (NSString *)urlString;
  16  - (void)post: (NSString *)urlString;
  17  
  18  @end

   1  //
   2  //  HTTP.m
   3  //
   4  
   5  #import "HTTP.h"
   6  
   7  
   8  @implementation HTTP
   9  
  10  @synthesize receivedData;
  11  
  12  - init {
  13      if ((self = [super init])) {
  14  		
  15      }
  16      return self;
  17  }
  18  
  19  - (void)dealloc {
  20      [super dealloc];
  21  }
  22  
  23  
  24  - (void)setDelegate:(id)val
  25  {
  26      delegate = val;
  27  }
  28  
  29  - (id)delegate
  30  {
  31      return delegate;
  32  }
  33  
  34  - (void)get: (NSString *)urlString {
  35  	
  36  	NSLog ( @"GET: %@", urlString );
  37  
  38  	self.receivedData = [[NSMutableData alloc] init];
  39  	
  40         NSURLRequest *request = [[NSURLRequest alloc]
  41  							 initWithURL: [NSURL URLWithString:urlString]
  42  							 cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
  43  							 timeoutInterval: 10
  44  							 ];
  45  
  46         NSURLConnection *connection = [[NSURLConnection alloc]
  47  								   initWithRequest:request
  48  								   delegate:self
  49  								   startImmediately:YES];
  50  	if(!connection) {
  51  		NSLog(@"connection failed :(");
  52  	} else {
  53  		NSLog(@"connection succeeded  :)");
  54  		
  55  	}
  56  	
  57  	[connection release];
  58          [request release];  
  59          [receivedData release];  
  60  }
  61  
  62  
  63  - (void)post: (NSString *)urlString {
  64  	
  65  	// POST
  66  	//[request setHTTPMethod:@"POST"];
  67  	// NSString *postString = @"Some post string";
  68  	//[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
  69  }	
  70  
  71  // ====================
  72  // Callbacks
  73  // ====================
  74  
  75  #pragma mark NSURLConnection delegate methods
  76  - (NSURLRequest *)connection:(NSURLConnection *)connection
  77  			 willSendRequest:(NSURLRequest *)request
  78  			redirectResponse:(NSURLResponse *)redirectResponse {
  79  	NSLog(@"Connection received data, retain count");
  80         return request;
  81  }
  82  
  83  
  84  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  85  	NSLog(@"Received response: %@", response);
  86  	
  87        [receivedData setLength:0];
  88  }
  89  
  90  - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  91  	NSLog(@"Received %d bytes of data", [data length]); 
  92  	
  93         [receivedData appendData:data];
  94  	NSLog(@"Received data is now %d bytes", [receivedData length]); 
  95  
  96  }
  97  
  98  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  99  	NSLog(@"Error receiving response: %@", error);
 100         [[NSAlert alertWithError:error] runModal];
 101  }
 102  
 103  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
 104         // Once this method is invoked, "responseData" contains the complete result
 105  	NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]); 
 106  	
 107  	NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
 108  	NSLog(@"Succeeded! Received %@ bytes of data", dataStr); 
 109  	
 110  	if ([delegate respondsToSelector:@selector(didFinishDownload:)]) {
 111  		NSLog(@"Calling the delegate"); 
 112  		//NSString* dataAsString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
 113  		[delegate performSelector:@selector(didFinishDownload:) withObject: dataStr];
 114  	}
 115  	
 116  	[dataStr release];
 117  }
 118  
 119  
 120  @end

Tagged http, objective-c, nsurlconnection