Search code examples
iosobjective-cnsurlnsurlsessionmbprogresshud

Get MBProgressHUD's progress from NSURL


I am trying to calculate the progress of my download method and show MBProgressHUD's progress during file is downloading , but I don't know how to calculate the progress float ! here is my code :

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

Solution

  • You can use RSNetworkKit. It has all handy methods for all network related calls, download and upload files with progress. It has internally implemented AFNetworking.

    https://github.com/rushisangani/RSNetworkKit

    RSDownlaodManager has a method to download any file with progress you can simple use like this.

    [[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) {
    
    }];