NSURLSession是iOS7.0 以后用来代替NSURLConnection的网络请求框架
NSURLSession有三中任务:dataTask, uploadTask, downLoadTask;
一,
//下载文件downloadTask
- (void)downloadFile{
//1创建session
NSURLSession *session = [NSURLSessionsharedSession];
//2.创建downloadtask
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/1.mp4"];
NSURLSessionDownloadTask *downloadTask = [sessiondownloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
/*
注意:保存的临时文件,在block回调执行完成之后,就自动删除
1.location从网络获取文件保存到本地的临时目录
2.response 响应头
3.错误
*/
NSLog(@"%@",location.path);
//拷贝文件到temp
NSFileManager *fileMan = [NSFileManagerdefaultManager];
/*
1.从A地考到b地
*/
NSString *fileSavePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"123"];
NSLog(@"%@",fileSavePath);
[fileMan copyItemAtPath:location.pathtoPath:fileSavePath error:NULL];
}];
//3.开启任务
[downloadTask resume];
}
_________________________________________________________________________
//带进度的下载
- (void)downloadFileWithProgress{
//1.session
/*
需要制定delegate sessionWithConfiguration
1.session的配置
2.代理对象
3.代理队列,代理方法将会在队列中执行
*/
NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSession *session = [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
//2.创建downloadtask
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/1.mp4"];
NSURLSessionDownloadTask *downloadTask = [sessiondownloadTaskWithURL:url];
//3.开启
[downloadTask resume];
}
#pragma mark delegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
//已经完成下载
//location 下载文件本地路径
//注意:::!!!!!在此代理昂发执行完成之前,需要拷贝文件
NSLog(@" finish : %@",location.path);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
/*
1.bytesWritten 本次服务器发送的数据长度
2.totalBytesWritten 已经下载了多少
3.totalBytesExpectedToWrite 文件的总大小
*/
//进度
float progress = totalBytesWritten *1.0 / totalBytesExpectedToWrite;
NSLog(@"%f",progress);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
//续传的时候调用
}
_________________________________________________________________________
断点续传:开始,暂停,继续
/*
问题:
1.开始.暂停,暂停,继续,崩溃
原因:resumeData nil
2.继续 ,崩溃
原因:resumeData nil
3.开始,暂停,多次继续进度混乱
原因:开启多次下载,下载有先有后,进度不一样,显示跳动
4.没有保存到沙盒,一断电数据没有
xcode6 NSURLSessionResumeInfoTempFileName 保存文件的完整路径
/Users/apple/Library/Developer/CoreSimulator/Devices/F67DB61C-9470-4154-BA5D-1C8F4B77E44C/data/Containers/Data/Application/60F9E930-C9DF-4E15-BF47-9DE4916BB68A/tmp/123
每次你新运行 60F9E930-C9DF-4E15-BF47-9DE4916BB68A可能会变
xocde7 文件名
*/
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property(nonatomic,strong)NSURLSession *session;
//下载任务
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;
//继续下载文件的信息
@property(nonatomic,strong)NSData *resumeData;
@property (weak, nonatomic) IBOutletUIProgressView *progressView;
@end
@implementation ViewController
//懒加载
-(NSURLSession *)session{
if(!_session){
NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];
_session = [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:nil];
}
return_session;
}
//开启下载
- (IBAction)beginClick:(id)sender {
[selfdownloadFileWithProgress];
}
//暂停下载
- (IBAction)pauseClick:(id)sender {
//返回当前下载文件的信息
[self.downloadTaskcancelByProducingResumeData:^(NSData *_Nullable resumeData) {
self.resumeData = resumeData;
NSLog(@"%@",resumeData);
//保存resumeData到沙盒
NSString *tmp =[NSTemporaryDirectory()stringByAppendingPathComponent:@"123"];
[resumeData writeToFile:tmp atomically:YES];
NSLog(@"%@",tmp);
}];
self.downloadTask =nil;
}
//点击继续
- (IBAction)resumeClick:(id)sender {
//从沙盒读取之前下载的信息
NSString *tmp =[NSTemporaryDirectory()stringByAppendingPathComponent:@"123"];
//判断文件是否存在
NSFileManager *fileMan = [NSFileManagerdefaultManager];
if([fileMan fileExistsAtPath:tmp]){
NSData *data =[NSDatadataWithContentsOfFile:tmp];
self.resumeData = data;
}
//判断resumeData
if(!self.resumeData){
return;
}
//继续下载,上次下载文件的信息
self.downloadTask = [self.sessiondownloadTaskWithResumeData:self.resumeData];
//开启下载
[self.downloadTaskresume];
self.resumeData =nil;
}
//带进度的下载
- (void)downloadFileWithProgress{
//1.创建downloadtask
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/1.mp4"];
self.downloadTask = [self.sessiondownloadTaskWithURL:url];
//2.开启
[self.downloadTaskresume];
}
#pragma mark delegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
//已经完成下载
//location 下载文件本地路径
//注意:::!!!!!在此代理昂发执行完成之前,需要拷贝文件
NSLog(@" finish : %@",location.path);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
/*
1.bytesWritten 本次服务器发送的数据长度
2.totalBytesWritten 已经下载了多少
3.totalBytesExpectedToWrite 文件的总大小
*/
//进度
NSLog(@"%@",[NSThreadcurrentThread]);
float progress = totalBytesWritten *1.0 / totalBytesExpectedToWrite;
NSLog(@"%f",progress);
self.progressView.progress = progress;
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
//续传的时候调用
}
_________________________________________________________________________
- (void)uploadFile{
//1.session
NSURLSession *session =[NSURLSessionsharedSession];
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/uploads/2.JPG"];//服务器的路径
//3请求
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
//put方式提交数据
request.HTTPMethod = @"put";
//Authorization: Basic YWRtaW46YWRtaW4= ----- admin:admin
[request setValue:[selfgetAuthWithUsername:@"admin"password:@"admin"]forHTTPHeaderField:@"Authorization"];
//文件的URL
NSURL *fileURL = [[NSBundlemainBundle] URLForResource:@"2.JPG"withExtension:nil];//需要上传的文件本地路径
//2.创建上传任务
NSURLSessionUploadTask *uploadTask = [sessionuploadTaskWithRequest:request fromFile:fileURL completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
/*
1.响应体
2.响应头
3.错误
*/
NSLog(@"%@",data);
NSLog(@"%@",response);
}];
//4 开启
[uploadTask resume];
}
//拼接Authorization
//Authorization: Basic YWRtaW46YWRtaW4= ----- admin:admin
-(NSString *)getAuthWithUsername:(NSString *)username password:(NSString *)password{
//1.拼接用户名和密码 admin:admin
NSString *str = [NSStringstringWithFormat:@"%@:%@",username,password];
//YWRtaW46YWRtaW4=
NSString *base64String = [selfbase64Encode:str];
return [NSStringstringWithFormat:@"Basic %@",base64String];
}
//base64编码
-(NSString *)base64Encode:(NSString *)str{
NSData *data = [strdataUsingEncoding:NSUTF8StringEncoding];
return [database64EncodedStringWithOptions:0];
}
_________________________________________________________________________
上传带进度
#import "ViewController.h"
@interface ViewController ()<NSURLSessionTaskDelegate>
@property(nonatomic,strong)NSURLSession *session;
@end
@implementation ViewController
//懒加载
-(NSURLSession *)session{
if(!_session){
NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];
_session = [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
}
return_session;
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[selfuploadFileWithProgress];
}
-(void)uploadFileWithProgress{
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/uploads/2.JPG"];
//3请求
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
//put方式提交数据
request.HTTPMethod = @"put";
//Authorization: Basic YWRtaW46YWRtaW4= ----- admin:admin
[request setValue:[selfgetAuthWithUsername:@"admin"password:@"admin"]forHTTPHeaderField:@"Authorization"];
//文件的URL
NSURL *fileURL = [[NSBundlemainBundle] URLForResource:@"2.JPG"withExtension:nil];
//2.上传任务
NSURLSessionUploadTask *uploadTask = [self.sessionuploadTaskWithRequest:request fromFile:fileURL];
//3.开启任务
[uploadTask resume];
}
//代理方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
/*
1.bytesSent 本次发送的数据长度
2.totalBytesSent 已经发送的数据长度
3.totalBytesExpectedToSend 要发送的文件总长度
*/
float progress = totalBytesSent * 1.0 / totalBytesExpectedToSend;
NSLog(@"%f",progress);
}
//拼接Authorization
//Authorization: Basic YWRtaW46YWRtaW4= ----- admin:admin
-(NSString *)getAuthWithUsername:(NSString *)username password:(NSString *)password{
//1.拼接用户名和密码 admin:admin
NSString *str = [NSString stringWithFormat:@"%@:%@",username,password];
//YWRtaW46YWRtaW4=
NSString *base64String = [self base64Encode:str];
return [NSString stringWithFormat:@"Basic %@",base64String];
}
//base64编码
-(NSString *)base64Encode:(NSString *)str{
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
return [data base64EncodedStringWithOptions:0];
}
@end
_____________________________________________________________________________________
dataTask:get方法(1,get方法一般用来获取浏览器上的数据,通过URL传递数据,不安全但是效率高,get请求的结果能被浏 览器缓存)URL中有中文或空格要进行URL编码,浏览器自动做编码转换.URL编码就是把汉字和空格还在那 换成% +16进制数的形式.
2,URL中的参数, ? 后面跟要传到服务器的参数(http协议的一部分),参数以键值对的形式传递,多个参数之间 使用&连接.
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/login.php?username=1111&password=111"];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *string = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}] resume];
_____________________________________________________________________________________
NSURL *url = [NSURLURLWithString:@"http://127.0.0.1/login.php"];
//创建request
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
//post
request.HTTPMethod = @"post";
//请求体
NSString *bodyString =@"username=1111&password=111";
request.HTTPBody = [bodyStringdataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:requestcompletionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
NSString *string = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}] resume];