我正在努力加快我的应用程序下载速度。我使用Asynchronous NSURLConnection从服务器下载内容,它通过一个连接正常工作。
我使用这篇文章中的代码来实现多个委托对象。 Multiple NSURLConnection delegates in Objective-C
当我创建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);
}
答案 0 :(得分:1)
您的代码看起来不错。我有一个类似的设置,成功运行(虽然似乎有四个并发连接的限制)。
您和我的代码之间的主要区别在于您在使用HTTP时使用FTP。为什么不尝试使用HTTP连接只是为了看看你是否在iPhone上遇到了FTP连接的限制?