使用前记得在info.plist里面导入网络协议
在此我使用的url是我本地的服务器 大家可以使用网上的接口下载尝试
/*
使用block方式下载数据 适合下载小文件 不能监听下载过程
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = @"http://127.0.0.1/设计模式解析.pdf";
str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
创建下载会话任务
NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
拼接文件路径,用来存放我们下载好的文件
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:response.suggestedFilename];
将返回的location转化成路径格式
NSString *temPath = [location path];
准备二进制数据
NSData *data = [NSData dataWithContentsOfFile:temPath];
创建文件处理对象
NSFileManager *fileManage = [NSFileManager defaultManager];
把下载好的文件写入到我们准备好的地址里去
[fileManage createFileAtPath:path contents:data attributes:nil];
}];
开始下载任务
[downLoadTask resume];
}
*/
-(void)viewDidLoad{
[super viewDidLoad];
//使用代理方式来下载文件 一般用来下载大一点的文件 可以监听下载过程
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/Office4mac.dmg"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]] ;
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
[downloadTask resume];
}
//监听下载的代理方法
//下载完成时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"user.mmm"];
NSString *temPath = [location path];
NSData *data = [NSData dataWithContentsOfFile:temPath];
NSFileManager *fileManage = [NSFileManager defaultManager];
[fileManage createFileAtPath:path contents:data attributes:nil];
}
//下载过程调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"这次共下载=%lld 当前下载总数= %lld 期待下载的总数%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end