如何发送异步URL请求?

时间:2011-12-15 05:46:07

标签: iphone ios xcode nsurlconnection nsurlrequest

我想知道如何仅从URL请求中异步获取返回值1或0 ....

目前我是这样做的:

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);

这是有效的,但它阻止了我的主线程,直到我从URL得到回复,我如何设置它以便它将在另一个线程而不是主线程中进行?

编辑:答案 我最终用这个来调用我的功能,效果很好:))

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

5 个答案:

答案 0 :(得分:28)

您可以使用NSURLConnection

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: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 

您可以找到NSURLConnection的实现

编辑:虽然Apple提供了NSURLConnection,但建议更多地放置网址请求。但我发现AFNetworking库非常节省时间,易于实现,并且作为第三方实现非常简单而且简单。你应该试一试。

答案 1 :(得分:24)

试试这个:

·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];
}

答案 2 :(得分:5)

使用NSURLConnection并提出您的请求。 然后,您可以使用NSURLConnection的方法启动同步或异步连接:

同步加载数据

+ sendSynchronousRequest:returningResponse:error:

异步加载数据

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

检查Apple Developer API Reference中的NSURLConnection类。

答案 3 :(得分:3)

https://gist.github.com/knmshk/3027474无耻地复制。所有积分都转到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];
                       }];

答案 4 :(得分:2)

iOS XCode文档中有一个名为LazyTableImages的示例。这会在滚动停止后将异步URL以及异步图像加载到屏幕上显示的UITableView单元格中。协议,异步数据处理等的优秀示例