【问题标题】:How to send Asynchronous URL Request?如何发送异步 URL 请求?
【发布时间】:2011-12-15 05:46:07
【问题描述】:

我想知道如何从 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];

【问题讨论】:

  • 从 iOS 5 开始,您可以改用+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler,这对于简单的请求来说比创建委托对象更容易、更清晰。稍后我会尝试写一个显示此方法的答案。
  • @MarkAmery 很高兴看到您的回答。我很难找到sendAsynchronousRequest 的简单示例。

标签: iphone ios xcode nsurlconnection nsurlrequest


【解决方案1】:

你可以使用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 的实现

编辑:虽然NSURLConnection 是由苹果提供的,但更推荐的方式是放置 URL 请求。但我发现AFNetworking 库非常节省时间,易于实现且健壮但与第三方实现一样简单。你应该试一试。

【讨论】:

  • 我应该使用哪种方法来获取 cookie 值??
【解决方案2】:

试试这个:

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

【讨论】:

  • 我只需要1或0的回复,这是不是太过分了?
  • @Maulik 添加“智能开发者”房间。
【解决方案3】:

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

同步加载数据

+ sendSynchronousRequest:returningResponse:error:

异步加载数据

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

查看 Apple Developer API 参考中的 NSURLConnection 类。

【解决方案4】:

无耻地抄袭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];
                       }];

【讨论】:

    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2015-06-09
      • 1970-01-01
      • 2018-04-26
      • 2016-11-22
      相关资源
      最近更新 更多