Showing the file download progress with NSURLSessionDataTask

前端 未结 4 632
感情败类
感情败类 2020-12-01 06:49

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

4条回答
  •  没有蜡笔的小新
    2020-12-01 07:14

    You need to implement following delegates:

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

提交回复
热议问题