21

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];
pkamb
  • 26,648
  • 20
  • 124
  • 157
Desmond
  • 4,943
  • 14
  • 51
  • 112
  • 5
    As of iOS 5, you can use `+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler` instead, which is easier and clearer for simple requests than creating a delegate object. I'll try to write up an answer showing this method later. – Mark Amery Jul 31 '13 at 15:30
  • 1
    @MarkAmery It would be nice to see your answer. I'm having difficulty finding a simple example of `sendAsynchronousRequest`. – Basil Bourque Jun 22 '14 at 23:44

5 Answers5

28

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.

Adil Soomro
  • 36,617
  • 9
  • 98
  • 146
24

try this :

.h:

NSMutableData *responseData;

.m:

- (void)load 
{
  NSURL *myURL = [NSURL URLWithString:@"http://www.example.com"];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

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

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
  responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
  [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
  [responseData release];
  [connection release];
  [textView setString:@"Unable to fetch data"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
  NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                                   length]);
  NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}
Dan J
  • 24,430
  • 17
  • 95
  • 168
Maulik
  • 19,108
  • 14
  • 80
  • 136
5

Use NSURLConnection and make your request. Then you may start synchronous or asynchronous connection with NSURLConnection's methods :

Loading Data Synchronously

+ sendSynchronousRequest:returningResponse:error:

Loading Data Asynchronously

+ connectionWithRequest:delegate:
– initWithRequest:delegate:
– initWithRequest:delegate:startImmediately:
– start

Check the NSURLConnection class in Apple Developer API Reference.

Saurabh Passolia
  • 8,059
  • 1
  • 24
  • 40
  • here's the link: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html – Saurabh Passolia Dec 15 '11 at 05:55
3

Shamelessly copy from https://gist.github.com/knmshk/3027474. All credits go to https://gist.github.com/knmshk.

xmlData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:
@"http://forrums.bignerdranch.com/smartfeed.php?"
@"limit=NO_LIMIT&count_limit20&sort_by=standard&"
@"feed_type=RSS2.0&feed_style=COMPACT"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:queue
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                           if (error) {
                               xmlData = nil;
                               NSLog(@"error:%@", error.localizedDescription);
                           }
                           [xmlData appendData:data];
                       }];
Jingshao Chen
  • 3,055
  • 1
  • 23
  • 32
2

There is an example in the iOS XCode documentation called LazyTableImages. This does an asynchronous URL as well as asynchronous image load into UITableView cells displayed on the screen after scrolling stops. Excellent example of protocols, asynchronous data handling, etc.

Jay Imerman
  • 4,308
  • 6
  • 35
  • 46