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

时间:2012-02-29 11:43:16

标签: iphone objective-c multithreading 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];
}

修改 *

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

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

  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self startImmediately:NO];
   [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
   [connection start];
   [connection release];

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

*的更新

在下面添加托马斯的回答(请注意,詹姆斯韦伯斯特的答案对于退出一个主题也是正确的)Apple文档解释说: “暂停状态 - 应用程序在后台但未执行代码。系统会自动将应用程序移动到此状态,并且在执行此操作之前不会通知它们。暂停时,应用程序仍保留在内存中但不执行任何代码。”< / p>

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

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

2 个答案:

答案 0 :(得分:1)

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

您确实应该在主runloop上安排连接(或使用GCD)。

设备锁定是另一个问题。设备锁定后,您的应用程序将暂停以延长电池寿命。您可以要求an extra amount of time when suspending以完成下载。

答案 1 :(得分:0)

我认为您的问题可能是,一旦退出startDownloading:消息,NSURLConnection就会被释放(或者更准确地说,当您的自动释放池耗尽时)

但是我认为你的方法论可能有点粗鲁。 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];

    [NSURLConnection connectionWithRequest:myURLRequest delegate:self];
}
相关问题