单独线程上的异步NSURLConnection无法调用委托方法

Zig*_*rth 6 iphone multithreading objective-c nsurlconnection nsurlconnectiondelegate

我在一个单独的线程上运行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];
}
Run Code Online (Sandbox Code Playgroud)

编辑*

我需要在一个单独的线程上运行NSURLConnection的原因是因为我在我的iPhone应用程序中下载了一些内容,并且当用户锁定屏幕时下载取消(如果用户只需按下主页按钮并且应用程序进入后台,则继续下载).我理解这是因为我在主线程上异步运行连接,而不是单独的.

我在启动NSURLConnection时也尝试过这段代码(不是在一个单独的线程中):

  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self startImmediately:NO];
   [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
   [connection start];
   [connection release];
Run Code Online (Sandbox Code Playgroud)

但是我在屏幕锁定上取消下载时遇到了同样的问题.

*更新

要在下面添加Thomas的答案(请注意James Webster的答案对于退出线程也是正确的)Apple文档解释说:"暂停状态 - 应用程序在后台但不执行代码.系统将应用程序移动到这种状态是自动的,并且在这样做之前不会通知它们.暂停时,应用程序仍保留在内存中但不执行任何代码."

由于当用户锁定屏幕时,应用程序处于后台状态而不是立即进入挂起状态,所有执行都会停止,从而导致任何下载,并且没有警告即将发生这种情况......可能存在一个通知,告诉我用户已锁定屏幕,但我还没有找到.

因此,当应用程序进入后台时,我暂停(保存某些信息并取消NSURLConnection)所有下载,并在再次激活时使用HTTP Range标头恢复它.这是一个可行但不理想的解决方法,因为下载不会在背景中发生,从而对用户体验产生负面影响......糟糕.

Tho*_*iau 1

由于您的 NSURLConnection 是异步的,因此您的 -startDownloading 方法会立即到达末尾,并且线程退出。

您确实应该在主运行循环上安排连接(或使用 GCD)。

设备锁定是另一个问题。当设备锁定时,您的应用程序将暂停以节省电池寿命。您可能可以在暂停时要求额外的时间来完成下载。