Getting data asynchronously instead of using initWithContentsOfURL

I am currently using this code to get data from a url: NSURL *url = [[NSURL alloc] initWithString:urlstring]; NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];

I was wondering how I can collect this data asynchronously so that my application doesn't hang every time I needed to do this. Thank!


source to share

5 answers

// Do not alloc init URL obj. for local use.
NSString *urlString = @"put your url string here";

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 


The above delegate methods refer to NSURLConnectionDelegate where you need to handle all things like response error, etc. This is provided by default, so we can directly override it without

I use it once in my project. It will work for an async request, but if you got the number of images, then use IconDownloader or EGOImageView , which implements lazy loading of the image and greatly reduce the chances of the application freezing.



The easiest way is available in os5 as follows:

NSString *stringfromFB;
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (data) {
        stringfromFB = [[NSString alloc] initWithData:data
                                             encoding:NSUTF8StringEncoding];  // note the retain count here.
    } else {
        // handle error


If you are stuck with os <5 for some reason, you will need to start connecting to a delegate and implement the delegate protocol as shown here (and in many places elsewhere).



You can do it with GCD:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSURL *url = [[NSURL alloc] initWithString:urlstring]; 
    NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url]




If you don't want to wait for the URL connection to complete, you can load it asynchronously using NSURLConnection.

[NSURLConnection connectionWithRequest:
  [NSURLRequest requestWithURL:
  [NSURL URLWithString:yourUrlString]]




Now that NSURLConnection is deprecated, you need to use NSURLSession.

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest: request
                                        completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) {

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

            if ([httpResponse statusCode] == STATUS_OK) {
                // use data                     
            else {
                NSLog(@"Network Session Error: %@", [networkError localizedFailureReason]);

[task resume];




All Articles