2016-02-09 2 views
0

Я пытаюсь рассчитать прогресс моего метода загрузки и показать прогресс MBProgressHUD во время загрузки файла, но я не знаю, как рассчитать ход выполнения! Вот мой код:Получите прогресс MBProgressHUD от NSURL

- (IBAction)preview:(id)sender { 

    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view]; 
    [self.navigationController.view addSubview:HUD]; 

    // Set determinate mode 
    HUD.mode = MBProgressHUDModeAnnularDeterminate; 

    HUD.delegate = self; 
    HUD.labelText = @"Loading"; 

    // myProgressTask uses the HUD instance to update progress 
    [HUD showWhileExecuting:@selector(downloadDataFromMac) onTarget:self withObject:nil animated:YES]; 

} 


- (void)downloadData { 

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

    NSURL *URL = [NSURL URLWithString:pathWithData]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 

     NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
     return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 


    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 

     NSLog(@"File downloaded to: %@", filePath); 

     //Hide HUD 
     [HUD hide:YES]; 

      self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePath]; 

      [self.documentInteractionController setDelegate:self]; 

      [self.documentInteractionController presentPreviewAnimated:YES]; 

     }]; 


    [downloadTask resume]; 

} 

EDITED:

- (void)downloadDataFromMac { 

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

    NSURL *URL = [NSURL URLWithString:pathWithData]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

    NSProgress *progress; 
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 

     [progress addObserver:self 
        forKeyPath:@"fractionCompleted" 
         options:NSKeyValueObservingOptionNew 
         context:NULL]; 

     NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 

     return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 



    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 

     NSLog(@"File downloaded to: %@", filePath); 

     //Hide HUD 
     [HUD hide:YES]; 

      self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePath]; 

      [self.documentInteractionController setDelegate:self]; 

      [self.documentInteractionController presentPreviewAnimated:YES]; 

     }]; 


    [downloadTask resume]; 

} 



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ 
    if ([keyPath isEqualToString:@"fractionCompleted"]) { 
     NSProgress *progress = (NSProgress *)object; 
     NSLog(@"Progress… %f", progress.fractionCompleted); 
     //do something with your progress here, for eg : 
     //but dont forget to first make HUD a class property so you can update it 
     [HUD setProgress:progress.fractionCompleted]; 

    } else { 
     [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; 
    } 
} 

ответ

1

Вы можете использовать RSNetworkKit. Он имеет все удобные методы для всех связанных с сетью вызовов, загрузки и загрузки файлов с прогрессом. Он внутренне реализовал AFNetworking.

https://github.com/rushisangani/RSNetworkKit

RSDownlaodManager имеет метод, чтобы загрузить любой файл с прогрессом вы можете просто использовать, как это.

[[RSDownloadManager sharedManager] downloadWithURL:@"URLString" downloadProgress:^(NSNumber *progress) { 

// show progress using HUD here 
// must use main thread to show progress or update UI. 

} success:^(NSURLResponse *response, NSURL *filePath) { 

} andFailure:^(NSError *error) { 

}]; 
+0

Я загрузил фреймворк, но и слежу за установкой, но все равно получаю эту ошибку 'RSNetworkKit.h не найден' !!!!!!!!! –

+0

вы пробовали с импортом ? – iOSEnthusiatic

+0

Да! Кажется, вы разработчик, пожалуйста, пришлите мне пример проекта? Почему вы так усложнили установку?! –

1

Вы можете добавить свойство NSProgress к определению NSURLSessionDownloadTask, а затем вы можете заметить, что свойство с помощью КВО. Так что, прежде чем создать задачу загрузки, создать свойство и добавить его в определении, например:

NSProgress *progress; 
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 

    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 

    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 



} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 

    NSLog(@"File downloaded to: %@", filePath); 

    //Hide HUD 
    [HUD hide:YES]; 

     self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePath]; 

     [self.documentInteractionController setDelegate:self]; 

     [self.documentInteractionController presentPreviewAnimated:YES]; 

    }]; 

[progress addObserver:self 
     forKeyPath:@"fractionCompleted" 
      options:NSKeyValueObservingOptionNew 
      context:NULL]; 
[downloadTask resume]; 

Тогда заметить, что свойство прогресса, как он меняется, добавьте этот метод в класс:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ 
if ([keyPath isEqualToString:@"fractionCompleted"]) { 
    NSProgress *progress = (NSProgress *)object; 
    NSLog(@"Progress… %f", progress.fractionCompleted); 
    //do something with your progress here, for eg : 
    //but dont forget to first make HUD a class property so you can update it 
    [self.hud setProgress:progress.fractionCompleted]; 

} else { 
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; 
} 
} 
+0

Спасибо, но я получаю эту ошибку '«NSProgress * __ сильный *»для параметра несовместимого типа«пустоте (^ _Nullable) (NSProgress * _Nonnull __strong)»' –

+0

Вы можете разместить свой код, где определен NSURLSessionDownloadTask? (все с блоками и т. д.) –

+0

Это так странно !!! Я просто проверял все подобные вопросы, и все ответы были одинаковыми! без ошибок !!! почему я получаю эту ошибку !!! –

Смежные вопросы