ios - 在 iOS 上,您能否发出同步网络请求(但不在主线程上)并仍然获得进度回调(在单独的非主线程上)?

标签 ios nsurlconnection grand-central-dispatch

在 iOS 上,您可以发出同步网络请求(离开主线程)并获得进度回调(在单独的非主线程上)吗?

我有一个串行(一次一个操作)后台队列,它运行所有不需要立即立即完成的耗时作业。不过,我确实想显示下载作业的进度。看起来您无法实例化 NSURLConnection 并配置委托(delegate),启动同步连接,然后获取进度回调。

有没有办法在那个后台队列上发出同步请求(同步是因为它背后的作业在完成之前不会开始),并且仍然得到可以发送的 setProgress: 回调更新进度条? (回调必须在不同的队列线程上,因为我的串行队列的线程在请求​​完成之前被阻塞。)

Apple's docs for NSURLConnection说同步请求实际上是建立在幕后的异步之上的。我必须重新实现吗?我需要一种方法来阻止线程,直到请求完成/失败。到目前为止,我获得的最佳线索是 NSOperationQueuewaitUntilFinished 方法,但我不想启动异步并持续轮询同步方法。

NSURLConnection Discussion

A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

最佳答案

在异步请求之上重新实现同步请求并不难。您只需要手动旋转线程的运行循环,直到您看到请求已完成(或失败)。这是一个粗略的例子:

NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:queryURL];
// Start the download and wait until it finishes
self.downloadFinished = NO;
self.downloader = [NSURLConnection connectionWithRequest:downloadRequest delegate:self];

while (!self.isDownloadFinished)
 {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
 }

下面是相关的 NSURLConnectionDelegate 方法:

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
 {
    self.downloadFinished = YES;
 }

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
 {
    NSLog(@"An error occurred: %@", error);
    self.receivedData = nil;
    self.downloadFinished = YES;
 }

关于ios - 在 iOS 上,您能否发出同步网络请求(但不在主线程上)并仍然获得进度回调(在单独的非主线程上)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471896/

相关文章:

java - 假设初始位置是(1, 1),看看你是否可以在每一步通过以下给定的规则到达(x, y)

ios - 查看Device中的核心数据表

objective-c - iOS6:UIViewController 无法加载名为 nib

ios - NSURLConnection 的委托(delegate)方法,请求authenticationChallenge 不会被解雇?

ios - 从 NSURLConnectionDataDelegate 设置内容时 UIWebView 重新加载 baseUrl

ios - 我的 iOS 委托(delegate)方法是否应该始终在主线程上返回?

ios - 来自 iTC 的无效 bundle 错误,无法提交应用程序 - 因为 4 个 swift dylibs 无法嵌入

ios - 在 ScrollView subview 中添加自定义 UIButton subview 会导致 CUICatalog : Invalid asset name supplied

iphone - 如何从运营商数据/3GS而不是wifi下载数据?

ios - 具有异步等待任务组的最大线程数