我正在尝试找出执行 NSURLConnection
异步请求的最佳方法,并在满足请求时使用警报 View 屏蔽 UI。我在让它与同步请求一起工作时遇到了很多麻烦,因为我无法弄清楚如何通过同步请求有效地使用多线程功能或操作队列,所以我认为这是最好的方法。伪代码或实际代码都可以,我只需要知道该往哪个方向走。到目前为止我认为:
- 创建
UIAlertView
属性 - 创建一个启动
NSURLConnection
的 void 函数,并在启动后立即显示 View - 使用委托(delegate)方法关闭 AlertView 窗口
-(void)connectionDidFinishLoading
或类似的方法。
就这么简单吗,还是我错过了什么?
最佳答案
最简单的方法可能是使用 UIApplication.networkActivityIndicatorVisible 属性,并在后台线程中执行同步请求。
-(void)loadURLInBackground:(NSURL*)url {
NSURLRequest* req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLResponse* response = nil;
NSError* err = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if( data != nil ) {
[self performSelectorOnMainThread:@selector(processData:) withObject:data waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:@selector(processError:) withObject:err waitUntilDone:NO];
}
}
使用[self PerformSelectorInBackground:@selector(loadURLInBackground:) withObject:url];
调用该方法,然后只需实现processData:
和processError:
。
关于iphone - NSURLConnection 异步请求并在满足请求时显示 "Loading"警报 View 或 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8314763/