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]];

    }

}

pic1.png 、 pic2.png 、 pic3.png の 3 つの写真があります。このコードを実行すると、アプリは pic3.png という名前の破損したファイルを 1 つだけ保存し、自動的にクラッシュします。3 つのファイルすべてをダウンロードする必要があります。

4

3 に答える 3

0

no.of REQUEST 操作を反復するために単純な while ループを使用しないでください。実際、Apple自体には非常に多くの組み込みライブラリがあります。ここで、「NSOPERATION QUEUE」を試すことをお勧めします。したがって、Apple 開発者サイトのメモを確認すると、明確なアイデアが得られます。 [1] https://developer.apple.com/library/IOs/documentation/Cocoa/Reference/NSOperationQueue_class/index.html

AddOperation、またはRemoveOperation、WaitUntilItFinishTheThreadのように、NSOperationを使用して異なるリクエストを処理する方法について..

于 2014-10-06T11:42:47.813 に答える
0

これが機能しないことは明らかです。3 つの非同期操作を開始します。非同期操作を開始するたびに、不明な場所にファイル名を保存しますが、おそらく同じ場所です。では、最初の非同期操作が終了したときにどのファイル名が使用されるのでしょうか? ヒント: 使用すると思われるものではありません。

于 2014-10-06T09:27:02.257 に答える
0

これを行う最善の方法は、実際にはすべての写真を 1 つの 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 に答える