【发布时间】:2012-02-29 11:43:15
【问题描述】:
我在单独的线程上运行 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 标头恢复它。 这是一种可行但不理想的解决方法,因为下载不是在后台进行的,这会对用户体验产生负面影响……真可惜。
【问题讨论】:
-
您用于 NSURLConnection 请求的方法本身是异步的,因此即使您不分离新线程,它也将是多线程操作。
-
编辑问题以更好地解释我的问题。
标签: iphone objective-c multithreading nsurlconnection nsurlconnectiondelegate