写了几种获取网络数据的方式和下载任务的方式
1.普通的request请求,block回调数据
{
/*******************普通request的请求,利用block接收*******************/
//1.获取资源
NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
//2.获取请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.创建会话
NSURLSession *session = [NSURLSession sharedSession];
//4.添加任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//错误检查
if (error != 0) {
NSLog(@"请求失败%@",error);
}else {
//状态码,响应头内容
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger status = httpResponse.statusCode;
NSDictionary *headerDic = httpResponse.allHeaderFields;
NSLog(@"status = %ld , headerFields = %@",status,headerDic);
//获取json数据
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"json = %@",jsonData);
}
}];
//5.发起任务 resume - 恢复
[dataTask resume];
}
2.自定义请求,block回调数据
/*******************自定义request的请求,利用block接收*******************/
NSURL *url = [NSURL URLWithString:@"http://piao.163.com/m/cinema/list.html?apiVer=6&city=110000"];
//创建可变Request对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//缓存策略
request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
//超时设置
request.timeoutInterval = 120;
//请求方式(默认是get)
request.HTTPMethod = @"POST";//这里的必须大写
//设置请求头 Accept-Language
[request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
//session(默认是异步)
NSURLSession *session = [NSURLSession sharedSession];
//添加任务(block)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//错误检查
if (error != nil) {
NSLog(@"请求失败%@",error);
}else {
//状态码,响应头内容
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger status = httpResponse.statusCode;
NSDictionary *headerDic = httpResponse.allHeaderFields;
NSLog(@"status = %ld , headerFields = %@",status,headerDic);
//获取json数据
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"json = %@",jsonData);
}
}];
[dataTask resume];
3.自定义session的方式,代理方式
代理方法:
NSURLSessionDataDelegate
内容:
/*******************自定义session,利用代理接收*******************/
NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
//设置请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//请求方式是get
[request setHTTPMethod:@"GET"];
//自定义session
//设置session的配置
//+defaultSessionConfiguration 用于创建默认类型的Session对象
//+ephemeralSessionConfiguration 用于创建临时类型的Session对象
//+backgroundSessionConfiguration:(NSString *)identifier 用于创建后台Session对象
//identifier:作用标示后台的session,做好和app的bundle id相同
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//缓存策略
config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
//蜂窝数据
config.allowsCellularAccess = YES;
/*
sessionWithConfiguration:session配置
delegate:代理 NSURLSessionDataDelegate
delegateQueue:代理队列 (主队列)
*/
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//直接获取请求,因为是代理方式
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
//resume
[dataTask resume];
代理方法:
#pragma makr- 代理方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
//响应头
NSLog(@"response : %@",response);
//必须写这句话继续接收响应体
//(block的回调)
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"heehhee");
NSLog(@"json - %@",jsonData );
}
4.下载一张图片
- (IBAction)nomalDownLoad:(UIButton *)sender {
//获取一个路径 ,一张图片
NSURL *url = [NSURL URLWithString:@"http://www.pptbz.com/pptpic/UploadFiles_6909/201204/2012041411433867.jpg"];
NSURLSession *session = [NSURLSession sharedSession];
//不设置request请求头,使用默认的
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//打印一下下载到的路径
//因为这个路径是一个临时文件所以需要把下载的东西移动到另外一个地方
NSLog(@"位置:%@",location);
//移动文件
NSFileManager *manager = [NSFileManager defaultManager];
NSString *newPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/download.jpg"];
NSURL *newURL = [NSURL fileURLWithPath:newPath];
[manager moveItemAtURL:location toURL:newURL error:nil];
NSLog(@"newURL : %@",newURL);
//图片就保存在了本地了
}];
[task resume];
}
5.下载一部电影,用进度条查看进度
头文件
__weak IBOutlet UIProgressView *progressView;
NSURLSessionDownloadTask *downTask;
//下载好的数据存起来
NSData *saveData;
NSURLSession *startSession;
这里使用的代理是
NSURLSessionDownloadDelegate
//能暂停的任务
- (IBAction)startDownLoad:(UIButton *)sender {
NSURL *url = [NSURL URLWithString:@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4"];
//填写一个配置
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//用代理来写,全局变量
startSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//建立一个下载任务,全局变量
downTask = [startSession downloadTaskWithURL:url];
//开始
[downTask resume];
}
- (IBAction)pause:(UIButton *)sender {
//暂停下载
[downTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {//已经下载好的数据
//定义一个全局变量来接收,在后面需要恢复下载
saveData = resumeData;
//安全释放
downTask = nil;
}];
}
//恢复下载
- (IBAction)going:(UIButton *)sender {
//这里的downtask已经不是之前的downtask了
//恢复到已经下载的数据
downTask = [startSession downloadTaskWithResumeData:saveData];
//继续任务
[downTask resume];
}
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"location:%@",location);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *newPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/01.mp4"];
NSURL *newURL = [NSURL URLWithString:newPath];
[manager moveItemAtURL:location toURL:newURL error:nil ];
NSLog(@"newURL:%@",newPath);
}
//每下载一个数据包调用一次
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
/*
bytesWritten -每次下载的数据包的大小
totalBytesWritten -已下载的数据
totalBytesExpectedToWrite -总数据大小
*/
NSLog(@"bytesWritten %lld , totalBytesWritten %lld,totalBytesExpectedToWrite %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
//进度条
float current = (float)totalBytesWritten /totalBytesExpectedToWrite;
progressView.progress = current;
}