iPhone - 如何下载大量文件

时间:2012-05-16 09:09:06

标签: iphone objective-c ios xcode cocoa-touch

我需要从服务器下载大量文件。最好的方法是什么? 所有文档都存储在NSMutableArray中,每个文档都有两个文件 - 文档本身及其更改日志。所以我所做的是:

- (void)downloadDocuments:(int)docNumber
{
    NSString *urlString;
    NSURL *url;   
    for (int i=0; i<[items count]; i++) {
        [progressBar setProgress:((float)i/[items count]) animated:YES];
        urlString = [[items objectAtIndex:i] docUrl];
        url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        [self downloadSingleDocument:url];
        urlString = [[items objectAtIndex:i] changeLogUrl];
        url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        [self downloadSingleDocument:url];
    }
    urlString = nil;
    url = nil;
    [self dismissModalViewControllerAnimated:YES];
}

- (void)downloadSingleDocument:(NSURL *)url
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req addValue:@"Basic XXXXXXX=" forHTTPHeaderField:@"Authorization"];
    downloadConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
    if (conn == downloadConnection) {
        NSString *filename = [[conn.originalRequest.URL absoluteString] lastPathComponent];
        filename = [filename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

        file = [[NSFileHandle fileHandleForUpdatingAtPath:filePath] retain];
        if (file)
        {
            [file seekToEndOfFile];
        }
    }

}


- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    if (conn == downloadConnection) {
        if (file) { 
            [file seekToEndOfFile];
        }
        [file writeData:data];
    }

}


- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{

    if (conn==downloadConnection) {
        [file closeFile];
    }
}

我的问题是只下载了最后一个文件。对我做错了什么建议? 在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题是您使用新的NSURLConnection实例(通过方法调用downloadSingleDocument)“覆盖”循环中的成员var“downloadConnection”。这样做会导致didReceiveResponse,didReceiveData和connectionDidFinish方法中的if语句仅使用最新创建的连接求值为true。尝试使用连接列表来避免这种情况。