我在一个单独的线程上运行 NSURLConnection (我知道它是异步的并且在主线程上运行时可以工作),但即使我将父线程作为委托传递,它也不会进行委托调用。有谁知道如何做到这一点?
代码:
-(void)startConnectionWithUrlPath:(NSString*)URLpath {
//initiates the download connection - setup
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
//initiates the download connection on a seperate thread
[NSThread detachNewThreadSelector:@selector(startDownloading:) toTarget:self withObject:self];
}
-(void)startDownloading:(id)parentThread {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[NSURLConnection connectionWithRequest:myURLRequest delegate:parentThread];
//The delegate methods are setup in the rest of the class but they are never getting called...
[pool drain];
}
编辑*
我需要在单独的线程上运行 NSURLConnection 的原因是因为我正在我的 iPhone 应用程序中下载一些东西,并且当用户锁定屏幕时下载会取消(如果用户只是按下主页按钮并且应用程序进入后台,它会继续正常)。我知道这是由于我在主线程上异步运行连接而不是单独运行连接。
在启动 NSURLConnection 时,我也尝试过这段代码(不在单独的线程中):
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
[connection release];
但是关于在屏幕锁定时取消下载,我有同样的问题。
*更新
为了在下面添加 Thomas 的答案(请注意,关于退出线程,James Webster 的答案也是正确的)Apple 文档解释说:“暂停状态 - 应用程序在后台但未执行代码。系统将应用程序移动到此状态自动并且在这样做之前不会通知他们。暂停时,应用程序保留在内存中但不执行任何代码。
由于当用户锁定屏幕时,应用程序会进入后台状态,而不是立即进入挂起状态,所有执行都会停止并终止任何下载,并且不会发出即将发生的警告......可能会有一条通知告诉我用户已锁定屏幕但我还没有找到。
因此,当应用程序进入后台时,我会暂停(保存某些信息并取消 NSURLConnection)所有下载,并在它再次激活时使用 HTTP Range 标头恢复它。这是一种可行的解决方法,但并不理想,因为下载不是在后台进行的,这会对用户体验产生负面影响……真可惜。