博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
下载文件 利用NSURLSession下载文件
阅读量:7154 次
发布时间:2019-06-29

本文共 7788 字,大约阅读时间需要 25 分钟。

hot3.png

NSURLSession----------------------------下载记得在工程里Info.plist中添加以下几项(切记 切记)Xcode7.0NSAppTransportSecurityNSAllowsArbitraryLoadsXcode7.1App Transport Security SettingsAllow Arbitrary Loads#import "ViewController.h"@interface ViewController ()
{    UITextField *textField;    UIButton *down;    UIButton *cancel;    UIButton *stop;    UIButton *regain;    UILabel *label;    UIProgressView *progress;    NSURLSessionDownloadTask *downLoad;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [self layout];}-(void)layout{    label = [[UILabel alloc]initWithFrame:CGRectMake(20, 130, 80, 30)];    label.textAlignment = NSTextAlignmentCenter;    label.layer.borderWidth = 2;    label.layer.borderColor = [UIColor blackColor].CGColor;    label.layer.cornerRadius = 7;    progress = [[UIProgressView alloc]initWithFrame:CGRectMake(10, 90, 355, 35)];        textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 30, 355, 35)];    textField.textAlignment = NSTextAlignmentCenter;    textField.layer.borderWidth = 2;    textField.layer.borderColor = [UIColor blackColor].CGColor;    textField.layer.cornerRadius = 7;    down = [[UIButton alloc]initWithFrame:CGRectMake(30, 590, 40, 30)];    [down setTitle:@"下载" forState:UIControlStateNormal];    [down setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    down.layer.borderWidth = 1;    down.layer.borderColor = [UIColor blackColor].CGColor;    down.layer.cornerRadius = 5;    [down addTarget:self action:@selector(down) forControlEvents:UIControlEventTouchUpInside];    cancel = [[UIButton alloc]initWithFrame:CGRectMake(120, 590, 40, 30)];    [cancel setTitle:@"取消" forState:UIControlStateNormal];    [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    cancel.layer.borderWidth = 1;    cancel.layer.borderColor = [UIColor blackColor].CGColor;    cancel.layer.cornerRadius = 5;    [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];    stop = [[UIButton alloc]initWithFrame:CGRectMake(220, 590, 40, 30)];    [stop setTitle:@"挂起" forState:UIControlStateNormal];    [stop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    stop.layer.borderWidth = 1;    stop.layer.borderColor = [UIColor blackColor].CGColor;    stop.layer.cornerRadius = 5;    [stop addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];    regain = [[UIButton alloc]initWithFrame:CGRectMake(320, 590, 40, 30)];    [regain setTitle:@"恢复" forState:UIControlStateNormal];    [regain setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    regain.layer.borderWidth = 1;    regain.layer.borderColor = [UIColor blackColor].CGColor;    regain.layer.cornerRadius = 5;    [regain addTarget:self action:@selector(regain) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:textField];    [self.view addSubview:down];    [self.view addSubview:cancel];    [self.view addSubview:stop];    [self.view addSubview:regain];    [self.view addSubview:label];    [self.view addSubview:progress];}-(void)down{    NSString *urlStr = textField.text;    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    NSURL *url = [NSURL URLWithString:urlStr];    //创建请求    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //创建session会话    //配置session(默认会话--单例)    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];    //请求超时时间    sessionConfig.timeoutIntervalForRequest = 10;    //是否允许蜂窝网络下载(2G/3G/4G)    sessionConfig.allowsCellularAccess = YES;    //创建会话    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理    //代理    downLoad = [session downloadTaskWithRequest:request];    [downLoad resume];}-(void)cancel{    [downLoad cancel];    }-(void)stop{    [downLoad suspend];}-(void)regain{    [downLoad resume];}//设置进度条状态-(void)setProgressStatus:(int64_t)totalBytesWritten expectedToWrite:(ino64_t)totalBytesExpectedToWrite{    //异步处理进度(获取主队列)    dispatch_async(dispatch_get_main_queue(), ^{      progress.progress = (float)totalBytesWritten/totalBytesExpectedToWrite;        if (totalBytesWritten == totalBytesExpectedToWrite) {            label.text = @"下载完成";            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;        }else{            label.text = @"正在下载";            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;        }    });}#pragma mark 下载任务代理#pragma mark 下载中(会多次调用,可以记录下载进度)-(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);    [self setProgressStatus:totalBytesWritten expectedToWrite:totalBytesExpectedToWrite];            }//下载完成-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{    NSLog(@"%@",location);    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];    path = [path stringByAppendingPathComponent:@"7170.jpg"];    NSLog(@"%@",path);    NSURL *saveUrl = [NSURL fileURLWithPath:path];    NSLog(@"%@",saveUrl);    //关键:复制文件 , 从location->saveUrl    NSError *error;    [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&error];    if (error) {        NSLog(@"%@",error.localizedDescription);    }    }#pragma mark 任务完成时调用,不管是否成功-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{    //如果有错误,打印一下    if (error) {        NSLog(@"%@",error.localizedDescription);    }}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end简化后的NSURLSession--------------------#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [self downloadFile];}-(void)downloadFile{    NSString *urlStr = @"http://b.zol-img.com.cn/desk/bizhi/image/6/2560x1600/1444631980385.jpg";    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    NSURL *url = [NSURL URLWithString:urlStr];    //创建请求    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //创建会话(这里使用一个全局会话)    NSURLSession *session = [NSURLSession sharedSession];    //创建下载任务    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if (!error) {            NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];            path = [path stringByAppendingPathComponent:@"图片7170.jpg"];            NSLog(@"%@",path);            NSURL *saveUrl = [NSURL fileURLWithPath:path];            NSError *errorSave;            [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&errorSave];            if (!errorSave) {                NSLog(@"保存成功");            }else{                NSLog(@"File Error is %@",errorSave.localizedDescription);            }        }else{            NSLog(@"下载出错:%@",error.localizedDescription);        }        }];    [downloadTask resume];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

转载于:https://my.oschina.net/u/2499339/blog/609055

你可能感兴趣的文章
一图胜千言,8张图理解Java
查看>>
[算法]动态规划之最长递增子序列
查看>>
好程序员告诉你Java架构师学习路线
查看>>
Redis之主从集群环境搭建
查看>>
tab切换小例子
查看>>
Java封装
查看>>
【快学springboot】9.使用 @Transactional 注解配置事务管理
查看>>
匿名对象方案与实体对象方案对比
查看>>
NTP服务放大攻击的解决办法
查看>>
SQL SERVER 占用资源高的SQL语句
查看>>
verdi使用
查看>>
The authenticity of host 'ip (ip)' can't be established.
查看>>
看博客学学Android(十八)
查看>>
lombok 安装
查看>>
virtualbox+centos 7 实现宿主机器互通
查看>>
Python爬虫学习笔记——防豆瓣反爬虫
查看>>
安装MySQL最后一步出现错误Error Nr.1045
查看>>
基于注解实现SpringBoot多数据源配置
查看>>
02 面向对象之:类空间问题以及类之间的关系
查看>>
20145234黄斐《Java程序设计》第九周学习总结
查看>>