ios 使用 NSURLSessionDataTask 显示文件下载进度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23987692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:14:59  来源:igfitidea点击:

Showing the file download progress with NSURLSessionDataTask

iosnsurlsessionnsurlsessiondownloadtasknsurlsessionconfiguration

提问by Kiran Patel

I want to display file download progress (how many bytes are received) of particular file. It works fine with the NSURLSessionDownloadTask .My question is I want to achieve the same with the NSURLSessionDataTask.

我想显示特定文件的文件下载进度(收到多少字节)。它与 NSURLSessionDownloadTask 一起工作得很好。我的问题是我想用 NSURLSessionDataTask 实现同样的目标。

Here is the code which receives file into NSData and writes to document folder:

这是将文件接收到 NSData 并写入文档文件夹的代码:

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

I am getting file size after write or complete datatask (after the file is received) :

我在写入或完成数据任务后获取文件大小(收到文件后):

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

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

But i want to display it's current bytes received status, is this possible with NSURLSessionDataTask?

但是我想显示它的当前字节接收状态,这可以用 NSURLSessionDataTask 吗?

回答by Alok SInha

You need to implement following delegates:

您需要实现以下委托:

<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

Also need to create two properties:

还需要创建两个属性:

@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;
}

回答by Alok SInha

You can also use NSURLSessionDownloadTask like following. Call startDownload methode.In .h file use this

您还可以使用 NSURLSessionDownloadTask 如下所示。调用 startDownload 方法。在 .h 文件中使用这个

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

回答by ricardopereira

Since iOS 11.0and macOS 10.13, URLSessionTask(former NSURLSessionTask) adopted the ProgressReporting protocol. That means you can use the progressproperty to track the progress of a session task.

iOS 11.0和 macOS 10.13 开始,URLSessionTask(前NSURLSessionTask采用了 ProgressReporting 协议。这意味着您可以使用该progress属性来跟踪会话任务的进度。

Expecting you already know how to use KVO observers, you can do something like:

期望您已经知道如何使用 KVO 观察者,您可以执行以下操作:

task = session.downloadTask(with: url)
task.resume()
task.progress.addObserver(self, forKeyPath: "fractionCompleted", options: .new, context: &self.progressKVOContext)

and observe the value with:

并观察值:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if context == &self.progressKVOContext, let keyPath = keyPath {
        switch keyPath {
        case "fractionCompleted":
            guard let progress = object as? Progress else {
                return
            }
            DispatchQueue.main.async { [weak self] in
                self?.onDownloadProgress?(progress.fractionCompleted)
            }
        case "isCancelled":
            cancel()
        default:
            break
        }
    }
    else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }
}

iOS 13 update

iOS 13 更新

OperationQueuehas now a progressproperty.

OperationQueue现在有一个progress属性

For example, the UIProgressViewcan observe that property and update the progress value automatically using the observedProgress. Full example in https://nshipster.com/ios-13/#track-the-progress-of-enqueued-operations.

例如,UIProgressView可以观察该属性并使用observedProgress. https://nshipster.com/ios-13/#track-the-progress-of-enqueued-operations 中的完整示例。

回答by yas375

import Foundation
import PlaygroundSupport

let page = PlaygroundPage.current
page.needsIndefiniteExecution = true

let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
let task = URLSession.shared.dataTask(with: url) { _, _, _ in
  page.finishExecution()
}

// Don't forget to invalidate the observation when you don't need it anymore.
let observation = task.progress.observe(\.fractionCompleted) { progress, _ in
  print(progress.fractionCompleted)
}

task.resume()