Search code examples
iphoneiosxcodensurlconnectionnsurlrequest

How to send Asynchronous URL Request?


I would like to know how do I get a return value 1 or 0 only.... back from an URL request asynchronously.

currently I do it in this way:

NSString *UTCString = [NSString stringWithFormat:@"http://web.blah.net/question/CheckQuestions?utc=%0.f",[lastUTCDate timeIntervalSince1970]];
NSLog(@"UTC String %@",UTCString);
NSURL *updateDataURL = [NSURL URLWithString:UTCString];
NSString *checkValue = [NSString stringWithContentsOfURL:updateDataURL encoding:NSASCIIStringEncoding error:Nil];
NSLog(@"check Value %@",checkValue);

this works, however it is blocking my main thread till I got a reply back from the URL, how do I set it so it will do it in a another thread instead of the main thread ?

EDIT: ANSWER I end upcalling my function with this, it works well :)

[self performSelectorInBackground:@selector(shouldCheckForUpdate) withObject:nil];

Solution

  • you can use NSURLConnection class

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
    

    and handle its response and errors using its delegate methods.

    - (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 
    

    You can find implementation of NSURLConnection

    Edit: Although NSURLConnection is provided by apple is more recommended way of placing URL request. But I found AFNetworking library very time saving, easy to implement and robust yet simple as third party implementation. You should give it a try.