iphone - 如何发送异步 URL 请求?

标签 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];

最佳答案

你可以使用 NSURLConnection

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

并使用其委托(delegate)方法处理其响应和错误。

- (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 是由 apple 提供的,但更推荐的放置 URL 请求的方式。但是我发现AFNetworking库非常节省时间,易于实现且强大但与第三方实现一样简单。你应该试一试。

关于iphone - 如何发送异步 URL 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8515667/

相关文章:

iphone - 将类传递给函数

iphone - xCode动态添加字段

objective-c - 我应该什么时候调用 removeObserver :forKeyPath from within a closing ViewController class that is observing a persistant Model class?

ios - 了解如何将 UISearchBar 与 Core Data 结合使用

ios - 如何使用 SpriteKit 根据点击来上下移动球?

ios - 在 Xcode 6 中使用私有(private)框架 "could not inspect application package"的应用程序。缺少框架 info.plist

iphone - 设置UITableViewCell删除控件的背景颜色

iphone - 为什么在 iOS6 上访问 SQLite 数据库需要更长的时间?

objective-c - Xcode/iTunes/Instruments 中央工具栏项;它叫什么,我如何创建一个?

iphone - 显示上一个日期的 DatePicker