6

我在一个单独的线程上运行 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 标头恢复它。这是一种可行的解决方法,但并不理想,因为下载不是在后台进行的,这会对用户体验产生负面影响……真可惜。

4

2 回答 2

1

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

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

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

于 2012-02-29T13:04:39.687 回答
0

我认为您的问题可能是 NSURLConnection 已在您退出startDownloading:消息后立即被释放(或更准确地说,当您的自动释放池耗尽时)

但是,我认为您的方法无论如何可能有点粗俗。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];
}
于 2012-02-29T11:51:16.283 回答