下载文件 利用NSURLSession下载文件

NSURLSession----------------------------
下载记得在工程里Info.plist中添加以下几项(切记 切记)
Xcode7.0
NSAppTransportSecurity
NSAllowsArbitraryLoads
Xcode7.1
App Transport Security Settings
Allow Arbitrary Loads

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
{
    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


你可能感兴趣的:(下载文件 利用NSURLSession下载文件)