奇怪的多个文件下载 - NSURLConnection

时间:2010-02-25 15:06:42

标签: iphone nsurlconnection

通过关注您的评论我遇到了问题。我想与不同的代表同时下载不同的文件:

·H:

NSMutableData *fileData;

的.m:

NSString *imgfile = [NSString stringWithFormat:@"http://xxxx/01.jpg"];
NSURL *fileURL1 = [NSURL URLWithString:imgfile];

NSString *audiofile = [NSString stringWithFormat:@"http://xxxx/01.mp3"];
NSURL *fileURL2 = [NSURL URLWithString:audiofile];

NSURLRequest *request1 = [NSURLRequest requestWithURL:fileURL1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0 ];
NSURLRequest *request2 = [NSURLRequest requestWithURL:fileURL2 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0 ];

NSArray *connections = [[NSArray alloc] initWithObjects:
[[NSURLConnection alloc] initWithRequest:request1 delegate:self ],
[[NSURLConnection alloc] initWithRequest:request2 delegate:self ],
nil];

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    fileData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [fileData appendData:data];        
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Unable to fetch data");
}
好的,下载过程有效,但是,jpg和mp3的文件大小不正确,唯一正确的是总文件大小(jpg + mp3),请你看看代码,缺少什么?

另一个问题是,我把文件放在NSMutableArray中,我的问题是,如何检查哪个数组索引是正确的文件类型(jpg和mp3)?因为我需要将它们保存到设备文件夹中。

2 个答案:

答案 0 :(得分:2)

看起来你的两个连接都写入同一个fileData对象,所有问题都来自于此 如何处理您可以看到relevant question在这里询问的多个连接,还有nice blog post包含NSURLConnection子类来解决此问题。

答案 1 :(得分:0)

这是我正在做的事情,我设置了一个计数器来识别要保存的文件类型:

  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
    [connection release];

   // Do something with the dataForConnection.

   downloadCount ++;

//  Copy Image Data to ur location using FileManager
//UIImage *img = [UIImage imageWithData:fileData];
NSString *saveDir;
if (downloadCount ==1)
    saveDir = [NSString stringWithFormat:@"001.jpg"];
if (downloadCount == 2)
    saveDir = [NSString stringWithFormat:@"001.mp3"];

//NSLog(@"saveDir=%@",saveDir);
NSArray  * sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString * filePath = [[NSString alloc] initWithFormat: @"%@/%@", [sysPaths objectAtIndex: 0], saveDir];
NSLog(@"filePath=%@",filePath);

if([dataForConnection writeToFile:filePath atomically:YES])
    NSLog(@"DONE COPYING");
else
    NSLog(@"Write to device error");
//[fileData setLength:0];

if (downloadCount == 2)
{
    downloadCount = 0;
    play the MP3 and display the image file;
}

}

即使我在模拟器上运行应用程序,文件下载时没有报错,但有时文件无法打开,即使我试图从文件夹中打开它,我被告知文件已损坏,我不明白出了什么问题,希望你明白我在说什么。