ios nsurlsession nsurlsessiondownloadtask nsurlsessionconfiguration

ios - Mostrando el progreso de descarga de archivos con NSURLSessionDataTask



nsurlsessiondownloadtask nsurlsessionconfiguration (2)

Necesitas implementar los siguientes delegados:

<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

También es necesario crear dos propiedades:

@property (nonatomic, retain) NSMutableData *dataToDownload; @property (nonatomic) float downloadSize; - (void)viewDidLoad { [super viewDidLoad]; NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]]; NSURL *url = [NSURL URLWithString: @"your url"]; NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url]; [dataTask resume]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { completionHandler(NSURLSessionResponseAllow); progressBar.progress=0.0f; _downloadSize=[response expectedContentLength]; _dataToDownload=[[NSMutableData alloc]init]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [_dataToDownload appendData:data]; progressBar.progress=[ _dataToDownload length ]/_downloadSize; }

Quiero mostrar el progreso de la descarga del archivo (cuántos bytes se reciben) de un archivo en particular. Funciona bien con NSURLSessionDownloadTask. Mi pregunta es que quiero lograr lo mismo con NSURLSessionDataTask.

Aquí está el código que recibe el archivo en NSData y escribe en la carpeta del documento:

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]]; NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:theRessourcesURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if(error == nil) { NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docsDir, Name]; NSLog(@"SIZE : %@",[NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]); [data writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error]; } }]; [dataTask resume];

Obtengo el tamaño del archivo después de escribir o completar la base de datos (después de recibir el archivo):

NSLog(@"SIZE : %@",[NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);

Pero quiero mostrar el estado actual de bytes recibidos, ¿es posible con NSURLSessionDataTask?


También puede utilizar NSURLSessionDownloadTask como sigue. Llame al archivo startDownload methode.In .h use este

- (void)startDownload { NSString *s; s = @"http://www.nasa.gov/sites/default/files/styles/1600x1200_autoletterbox/public/pia17474_1.jpg?itok=4fyEwd02"; NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:[NSURL URLWithString:s]]; [task resume]; } - (NSURLSession *) configureSession { NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.neuburg.matt.ch37backgroundDownload"]; config.allowsCellularAccess = NO; // ... could set config.discretionary here ... NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; return session; } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { CGFloat prog = (float)totalBytesWritten/totalBytesExpectedToWrite; NSLog(@"downloaded %d%%", (int)(100.0*prog)); } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { // unused in this example } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSData *d = [NSData dataWithContentsOfURL:location]; UIImage *im = [UIImage imageWithData:d]; dispatch_async(dispatch_get_main_queue(), ^{ self.image = im; }); } -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"completed; error: %@", error); }