【发布时间】: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