gpt4 book ai didi

iphone - 单独线程上的异步 NSURLConnection 无法调用委托(delegate)方法

转载 作者:太空狗 更新时间:2023-10-30 03:45:39 24 4
gpt4 key购买 nike

我在一个单独的线程上运行一个 NSURLConnection(我知道它是异步的并且在主线程上运行时工作),但即使我将父线程作为委托(delegate)传递,它也不会进行委托(delegate)调用。有谁知道如何做到这一点?

代码:

-(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 header 恢复它。这是一个可行但不理想的解决方法,因为下载不是在后台发生的,这会对用户体验产生负面影响……真可惜。

最佳答案

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

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

设备锁是另一个问题。当设备被锁定时,您的应用程序将暂停以节省电池生命周期。你或许可以要求 an extra amount of time when suspending以便完成下载。

关于iphone - 单独线程上的异步 NSURLConnection 无法调用委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com