奇怪的多个文件下载-NSURLConnection [英] strange multiple files download - NSURLConnection

查看:33
本文介绍了奇怪的多个文件下载-NSURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关注您的评论时遇到了问题.我想同时使用不同的代表下载不同的文件:

I encounter a problem by following your comment. I would like to download different file at same time with different delegate:

.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),请看一下代码,缺少什么?

ok, the download process works, but, the file size of jpg and mp3 are incorrect, the only correct thing is the total file size (jpg+mp3), please could you have a look on the code, what is missing?

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

Another question is, I put the file in a NSMutableArray, my question is, how to check which index of array is the correct file type (jpg and mp3)? because I need to save them to the device folder.

推荐答案

看起来您的两个连接都写入同一个 fileData 对象,并且随之而来的是所有问题.
如何处理多个连接,您可以在此处看到相关问题不错的博客帖子包含用于解决此问题的 NSURLConnection 子类.

It looks like both your connections write to the same fileData object and all your problems follow from that.
How to deal with multiple connections you can see relevant question asked here on SO, there's also nice blog post containing NSURLConnection subclass that addresses this issue.

这篇关于奇怪的多个文件下载-NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆