ios - 从 NSURL 获取 MBProgressHUD 的进度

标签 ios objective-c nsurl nsurlsession mbprogresshud

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

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

最佳答案

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

}];

关于ios - 从 NSURL 获取 MBProgressHUD 的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35291782/

相关文章:

cocoa - NSURL URLWithString : is null with non-english accented characters

ios - 使用 AutoLayout 调整 UICollectionViewCell 及其内容的大小

ios - 锁定和解锁屏幕 - iPad

ios - 如何在 objective-c 中使用 nsurl 在 url 查询参数中传递数组?

objective-c - 通过 PodioKit API 将经度和纬度值放入 map 字段中?

ios - 从 NSString 创建KeychainValue

ios - 如何在 iOS 9 中启用 App Transport Security 的情况下加载 HTTP URL?

ios - iOS CLLocationManager 类和常量的错误

ios - GPUImage : YUV or RGBA impact on performance?

ios - 如何制作一个按钮来检索最新的信息集?