Search code examples
iphoneasynchronousnsstringnsurl

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


Solution

  • // 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.