3

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 could gather this data asynchronously so that my app does not freeze everytime I need to execute this. Thanks!

Prajoth
  • 900
  • 3
  • 12
  • 26

5 Answers5

8

The simplest way is available in os5 like this:

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're stuck in os<5 for some reason, you'll need to start your connection with a delegate, and implement the delegate protocol as illustrated here (and many places elsewhere).

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
4

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]
});
LuisEspinoza
  • 8,508
  • 6
  • 35
  • 57
  • Does GCD automatically do multi-threading for you? Sorry if simple question, I have no experience with this yet. Thanks! – Jack Humphries Mar 24 '12 at 03:00
  • if you use dispatch_async and dispatch_get_global_queue, YES. It's a implementation of TASK PARALELISM, very easy to use and very powerful (supports multi-core). You can read about it: http://en.wikipedia.org/wiki/Grand_Central_Dispatch and https://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html . Is always my first choice for paralelism in iOS. – LuisEspinoza Mar 25 '12 at 00:00
0

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];
Reefwing
  • 2,242
  • 1
  • 22
  • 23
0

if you don’t want to wait for a connection to complete loading a url, you can load it asynchronously using NSURLConnection.

[NSURLConnection connectionWithRequest:
  [NSURLRequest requestWithURL:
  [NSURL URLWithString:yourUrlString]]
   delegate:self];
Malek_Jundi
  • 6,140
  • 2
  • 27
  • 36
0
// 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 are of NSURLConnectionDelegate, where you need to handle all things like response error etc.. It is by default provided so we can directly override it without

I have use once in my project It will work for async request but If you received number of images as well then also use IconDownloader or EGOImageView which implements the lazy loading of image and make much low chances of freezing of app.

iDhaval
  • 7,824
  • 2
  • 21
  • 30