Aug 12, 2008

(Objective-C) How to use NSURLConnection

Create an object of NSMutableURLRequest, you can set the header field in this object. And then create an object of NSURLConnection with the parameter of NSMutableURLRequest and delelgate (its self).

The start method "start" is not necessary, in my case i got application crashed when i add start method. Don't forget set up a timer
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
after the start method.

The last thing is use the delegate methods of NSURLConnection, such as:
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
(void)connectionDidFinishLoading:(NSURLConnection *)connection

In these method, you can check the status of connection, received data and cancel the connectin in connectionDidFinishLoading.


moeen uddin said...

In my resposnse recieved data i m getting bytes of stream, I m unable to convert it into string. My url returns a binary data.Can you help

Nan said...

Hi, use initWithBytes of nsstring to convert your data, here is an example of conversion nsdata to nsstring:
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length] encoding: NSUTF8StringEncoding];