Cel C: Pobieranie pliku z paskiem postępu [duplikat]

To pytanie ma już odpowiedź tutaj:

Próbuję umieścić pasek postępu, który synchronizuje się podczas pobierania, które się dzieje. Moja aplikacja może teraz pobrać plik za pomocą tego kodu...

    pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://webaddress.com/pro/download/file.pdf"]];

    NSString *resourcePDFPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    pdfFilePath = [resourcePDFPath stringByAppendingPathComponent:@"myPDF.pdf"];

    [pdfData writeToFile:pdfFilePath atomically:YES];

Podczas procesu tego kodu aplikacja zatrzymana podczas pobierania, czy to normalne? Teraz chcę umieścić pasek postępu podczas tego czasu zatrzymania podczas pobierania.

Próbowałem sprawdzić kody, które znalazłem w Internecie, ale jestem trochę zdezorientowany, myślę, że potrzebuję krok po kroku-dobrze wyjaśnionego odniesienia.

Author: SeongHo, 2013-05-09

4 answers

Using AFNetworking,

Tutaj postęp jest UIProgressview

#import <AFNetworking/AFNetworking.h>//add to the header of class

-(void)downloadShowingProgress
{
   progress.progress = 0.0;

    currentURL=@"http://www.selab.isti.cnr.it/ws-mate/example.pdf";


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MY_FILENAME_WITH_EXTENTION.pdf"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, NSUInteger totalBytesRead, NSUInteger totalBytesExpectedToRead) {
        progress.progress = (float)totalBytesRead / totalBytesExpectedToRead;

    }];

    [operation setCompletionBlock:^{
        NSLog(@"downloadComplete!");

    }];
    [operation start];

}

Korzystanie Z NSURLConnection

-(void)downloadWithNsurlconnection
{

    NSURL *url = [NSURL URLWithString:currentURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    progress.hidden = NO;
    [receivedData setLength:0];
    expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
    float progressive = (float)[receivedData length] / (float)expectedBytes;
    [progress setProgress:progressive];


}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:    (NSCachedURLResponse *)cachedResponse {
    return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".mp3"]];
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [receivedData writeToFile:pdfPath atomically:YES];
    progress.hidden = YES;
}
 60
Author: Lithu T.V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-23 07:37:59

Użyj ASIHTTPRequest.Klasa h I ASINetworkQueue.h do pobrania pliku.

I użyj tego kodu dla paska postępu

    request = [ASIHTTPRequest requestWithURL:@"http://webaddress.com/pro/download/file.pdf];
    [request setDelegate:self];
    [request setDownloadProgressDelegate:progressView];
    [request setShowAccurateProgress:YES];
    request.shouldContinueWhenAppEntersBackground=YES;
    request.allowResumeForFileDownloads=YES;
    [request startAsynchronous];
To może Ci pomóc.]}
 1
Author: Nithinbemitk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-09 03:35:46

Obawiam się, że to nie jest normalne, użyj metody asynchronicznej, aby uzyskać NSData.

 0
Author: waterforest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-09 03:32:34

Przede wszystkim należy wyjaśnić, czy wykonać połączenie synchroniczne, czy asynchroniczne. W przypadku aplikacji mobilnych lub innych aplikacji preferowany jest asynchroniczny.

Kiedy już będziesz czysty użyj NSURLConnection klasa pobierająca dane z adresu URL. Oto dobry tutorial .

I do ładowania można rozpocząć postęp podczas uruchamiania żądania i zatrzymać go po otrzymaniu metody connection:didFailWithError: LUB connectionDidFinishLoading: delegate.

 0
Author: Inder Kumar Rathore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-09 04:14:46