我想创建一个类,将同时处理多个下载(我需要下载很多小文件),我有“消失”连接的问题。iPhone上的并发背景下载
我有addDonwload函数,它将url添加到URL下载列表中,并检查是否有可用的免费下载插槽。如果有一个,它立即开始下载。当其中一个下载完成时,我选择第一个url表单并开始新的下载。
我使用NSURLConnection的下载,这里是一些代码
- (bool) TryDownload:(downloadInfo*)info
{
int index;
@synchronized(_asyncConnection)
{
index = [_asyncConnection indexOfObject:nullObject];
if(index != NSNotFound)
{
NSLog(@"downloading %@ at index %i", info.url, index);
activeInfo[index] = info;
NSURLRequest *request = [NSURLRequest requestWithURL:info.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
[_asyncConnection replaceObjectAtIndex:index withObject:[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE]];
//[[_asyncConnection objectAtIndex:i] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
return true;
}
}
return false;
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
[self performSelectorOnMainThread:@selector(DownloadFinished:) withObject:connection waitUntilDone:false];
}
- (void)DownloadFinished:(id)connection
{
NSInteger index = NSNotFound;
@synchronized(_asyncConnection)
{
index = [_asyncConnection indexOfObject:(NSURLConnection*)connection];
}
[(id)activeInfo[index].delegate performSelectorInBackground:@selector(backgroundDownloadSucceededWithData:) withObject:_data[index]];
[_data[index] release];
[activeInfo[index].delegate release];
@synchronized(_asyncConnection)
{
[[_asyncConnection objectAtIndex:index] release];
[_asyncConnection replaceObjectAtIndex:index withObject:nullObject];
}
@synchronized(downloadQueue)
{
[downloadQueue removeObject:activeInfo[index]];
[self NextDownload];
}
}
- (void)NextDownload
{
NSLog(@"files remaining: %i", downloadQueue.count);
if(downloadQueue.count > 0)
{
if([self TryDownload:[downloadQueue objectAtIndex:0]])
{
[downloadQueue removeObjectAtIndex:0];
}
}
}
_asyncConnection是我的下载时段(NSURLConnections)的阵列 downloadQueue是URL列表,下载
会发生什么情况是,一开始一切正常,但几次下载后,我的连接开始消失。下载开始,但连接:didReceiveResponse:永远不会被调用。输出控制台有一件事情,我不明白我可能会有所帮助。通常在我的NSLog消息之前有一些类似于应用程序名称[3057:207] 2010-01-24 21:44:17.504。我想方括号中的数字是某种应用程序:线程ID?一切工作正常,虽然有相同的号码,但一段时间后,“NSLog(@”下载%@在索引%i“,info.url,索引);”消息开始有不同的第二个数字。当发生这种情况时,我停止接收该urlconnection的任何回调。
由于我有严格的最后期限,我无法找到问题,这一直让我疯狂。我没有很多iphone开发和多线程应用程序的经验。我一直在尝试不同的方法,所以我的代码有点杂乱,但我希望你会看到我在这里试图做的:)
btw是你们中的任何人都知道现有的类/ lib我可以使用,这将是有益的以及。我想要平行下载能力o动态添加新的文件下载(所以初始化下载器在所有的URL对我没有帮助)
感谢您的提示。我完全重写了我的课,并按预期工作。对不起,但我完全忘记了这是很久以前解决的:) – Lope 2010-10-21 21:46:07