sincronizar readdle google descargar cómo con como archivos app ios objective-c download uiprogressview

ios - readdle - Objetivo C: Descargar archivo con barra de progreso



documents app ipad (4)

En primer lugar, debe tener claro si hacer una llamada síncrona o asíncrona. Para aplicaciones móviles o cualquier otra aplicación, se prefiere una asíncrona.

Una vez que esté claro, use la clase NSURLConnection para obtener los datos de la URL. Aquí está el buen tutorial .

Y para cargar, puede iniciar el progreso mientras inicia la solicitud y detenerla cuando recibe la connection:didFailWithError: o connectionDidFinishLoading: método delegado.

Estoy tratando de poner una barra de progreso que se sincronice durante la descarga que está sucediendo. Mi aplicación ahora puede descargar un archivo usando estos códigos ...

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

Durante el proceso de este código, la aplicación se detuvo durante la descarga, ¿es normal? Ahora lo que quiero es poner una barra de progreso durante ese tiempo de detención mientras se descarga.

Intenté buscar en los códigos que encontré en línea, pero estoy un poco confundido, creo que necesito una referencia explicada paso a paso.


Me temo que no es normal, use un método asíncrono para obtener el NSData.


Use la clase ASIHTTPRequest.h y ASINetworkQueue.h para descargar el archivo.

y usa este código para la barra de progreso

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

esto puede ayudarte


Utilizando AFNetworking ,

Aquí el progreso es el 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]; }

Utilizando 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; }