#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.url
NSString *str = @"http://localhost/images.zip";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:str];
//2.实例化一个session对象
//NSURLSessionConfiguration可以配置全局访问的参数
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//3.指定回调方法工作的线程
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
//4.发起并且继续任务
[[session downloadTaskWithURL:url] resume];
}
#pragma mark - NSURLSessionDownloadDelegate
/**
* 1.下载完成后被调用的方法(iOS7和iOS8都必须实现)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"下载完成");
}
/**
* 2.下载进度变化的时候被调用。多次调用。(iOS8可以不实现)
*
* @param bytesWritten 本次写入的字节数
* @param totalBytesWritten 已经写入的字节数
* @param totalBytesExpectedToWrite 总的下载字节数
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"%f",progress);
}
/**
* 3.断点续传的时候被调用的方法。(一般上面都不用写,iOS8可以不实现)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
@end
NSURLSession下载的进度监测
最新推荐文章于 2020-05-09 08:02:30 发布