从 NSURL 获取 MBProgressHUD 的进度

Get MBProgressHUD's progress from NSURL

我正在尝试计算我的下载方法的进度并在文件下载期间显示 MBProgressHUD 的进度,但我不知道如何计算浮动进度!这是我的代码:

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

}

已编辑:

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

您可以将 NSProgress 属性 添加到 NSURLSessionDownloadTask 定义中,然后您可以使用 KVO 观察 属性。因此,在创建下载任务之前,创建 属性 并将其添加到定义中,如下所示:

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

然后观察进度 属性 的变化,将此方法添加到您的 class :

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

您可以使用 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) {

}];