我正在尝试加快我的应用程序下载速度。我使用异步 NSURLConnection 从服务器下载内容,一个连接就可以正常工作。
我使用这篇文章中的代码来实现多个委托对象。Objective-C 中的多个 NSURLConnection 委托
当我创建 2 个 NSURLConnection 对象时,每个对象都在尝试下载不同的文件。回调 didReceiveData 例程被调用,但它只接收第一个 NSURLConnection 对象的数据,直到第一个连接完成,然后它开始从第二个 NSURLConnection 接收数据。我希望这两个连接同时接收数据,我该怎么办?这是我当前的代码。
-(IBAction) startDownloadClicked :(id) sender
{
while (bDownloading)
{
int nCurrentCon = 0;
while (nCurrentCon < 2)
{
[self downloadAFile:[filenameArray objectAtIndex:nCurrentCon]];
nCurrentCon++;
}
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
}
- (void) downloadAFile: (NSString*) filename
{
NSString* urlstr = @"ftp://myftpusername:password@hostname";
NSURLRequest* myreq = [NSURLRequest requestWithURL:[NSURL URLWithString:urlstr]];
DownloadDelegate* dd = [[DownloadDelegate alloc] init]; //create delegate object
MyURLConnection* myConnection = [[MyURLConnection alloc] initWithRequest:myreq delegate:dd
startImmediately:YES];
}
然后在我的委托对象中,我实现了这些例程
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receiveBuffer setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"receiving data for %@", targetFileName); //the file name were set when this delegate object is initialized.
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Download Failed with Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"File %@ - downloaded.", targetFileName);
}