我正在尝试创建可以同时处理多个下载的类(我需要下载很多小文件),并且我遇到了“消失”连接的问题。
我有函数 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 列表
发生的情况是,一开始一切正常,但下载几次后我的连接开始消失。下载开始,但 connection:didReceiveResponse: 永远不会被调用。输出控制台中有一件我不明白的事情可能会有所帮助。通常有类似的东西
2010-01-24 21:44:17.504 应用程序名称[3057:207]
在我的 NSLog 消息之前。我猜方括号中的数字是某种 app:thread id?当数字相同时,一切正常,但一段时间后,“NSLog(@“在索引 %i 处下载 %@”,info.url,索引);”消息开始具有不同的第二个数字。当这种情况发生时,我将停止接收该 urlconnection 的任何回调。
这让我抓狂,因为我有严格的期限,而且我找不到问题。我对 iPhone 开发和多线程应用程序没有太多经验。我一直在尝试不同的方法,所以我的代码有点混乱,但我希望你能看到我在这里尝试做的事情:)
顺便说一句,你们中的任何人都知道我可以使用的现有类/库,这也会有帮助。我想要并行下载并能够动态添加要下载的新文件(因此在开始时使用所有网址初始化下载器对我来说没有帮助)