2

我正在尝试在使用此代码时同时从我自己的服务器下载几个文件:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // create
    [[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil];
    _file = [NSFileHandle fileHandleForUpdatingAtPath:strFilePath];// read more about file handle
    if (_file)   {
        [_file seekToEndOfFile];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata
{
    //write each data received
    if( receivedata != nil){
        if (_file)  {
            [_file seekToEndOfFile];
        }
        [_file writeData:receivedata];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
    //close file after finish getting data;
    [_file closeFile];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //do something when downloading failed
}
- (IBAction)downloadFromServer:(id)sender {

        NSLog(@"File now being downloaded");
    while (i<=3) {

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSURL *strFileURL =[NSURL URLWithString:[NSString stringWithFormat:@"SomePath/pic%d.png", i]];

    [request setURL:strFileURL]; 
    NSURLConnection *conection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [conection start];
    strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic%d.png", i]];

    }

}

我有 3 张图片,pic1.png、pic2.png 和 pic3.png。现在,如果我运行此代码,该应用程序将只保存一个名为 pic3.png 的损坏文件并自动崩溃。我需要下载所有三个文件,我哪里出错了?

4

3 回答 3

0

很明显,这是行不通的。您启动三个异步操作。每次启动异步操作后,您都将文件名存储在未知位置,但可能是相同的位置。那么当第一个异步操作完成时会使用什么文件名呢?提示:不是你认为它会使用的那个。

于 2014-10-06T09:27:02.257 回答
0

不要使用简单的 while 循环来迭代 no.of REQUEST 操作。实际上,Apple 本身就有很多内置库。所以在这里最好的一个我建议你尝试“NSOPERATION QUEUE”。所以,最好你可以查看 Apple 开发者网站 Notes,然后你就会有一个清晰的想法:[1] https://developer.apple.com/library/IOs/documentation/Cocoa/Reference/NSOperationQueue_class/index.html

对于如何使用 NSOperation 处理不同的请求 - 如 AddOperation、或 RemoveOperation、WaitUntilItFinishTheThread..

于 2014-10-06T11:42:47.813 回答
0

最好的方法实际上是将所有图片放在一个 zip 文件中,下载并使用以下代码在真实设备上解压缩:

    dispatch_queue_t queue = dispatch_get_global_queue(
                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSURL *url = [NSURL URLWithString:@"someDirectory/newPics.zip"];
        NSError *error = nil;
        // 2
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];

        if(!error)
        {
            // 3
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *path = [paths objectAtIndex:0];
            NSString *zipPath = [path stringByAppendingPathComponent:@"newPics.zip"];

            [data writeToFile:zipPath options:0 error:&error];

            if(!error)
            {

                ZipArchive *za = [[ZipArchive alloc] init];
                // 1
                if ([za UnzipOpenFile: zipPath]) {
                    // 2
                    BOOL ret = [za UnzipFileTo: path overWrite: YES];
                    if (NO == ret){} [za UnzipCloseFile];

                    // 3
                    NSString *imageFilePath = [path stringByAppendingPathComponent:@"newPics/pic1.png"];
                    //[self removeImage:zipPath];


                    [[NSFileManager defaultManager] removeItemAtPath:zipPath error: &error];

                    dispatch_async(dispatch_get_main_queue(), ^{

                            NSURL *fileURL = [NSURL fileURLWithPath:imageFilePath];
                            [_webV loadRequest:[NSURLRequest requestWithURL:fileURL]];



                    });

                }

            }
            else
            {
                NSLog(@"Error saving file %@",error);
            }
        }
        else
        {
            NSLog(@"Error downloading zip file: %@", error);
        }

    });

这是最好的方法,快速可靠。

于 2014-10-06T13:31:52.363 回答