NSURLSession相关
使用步骤:使用NSURLSession对象创建NSURLSessionTask,然后执行Task
Task的类型:
NSURLSessionDataTask 主要用于Http请求等
NSURLSessionDownloadTask 主要用于下载文件
NSURLSessionUploadTask 主要用于上传文件
NSURLSession实现get
方法一:
- (void)httpGet1
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//该Block的执行实际上实在子线程中执行的,如果需要做类似于更新UI的主线程操作,还需要切换主线程
NSLog(@"%@",[NSThread currentThread]);
}];
[task resume];
}
方法二:
- (void)httpGet2
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//该Block的执行实际上实在子线程中执行的,如果需要做类似于更新UI的主线程操作,还需要切换主线程
NSLog(@"%@",[NSThread currentThread]);
}];
[task resume];
}
NSURLSession实现post
- (void)httpPost
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//该Block的执行实际上实在子线程中执行的,如果需要做类似于更新UI的主线程操作,还需要切换主线程
NSLog(@"%@",[NSThread currentThread]);
}];
[task resume];
}
NSURLSession用代理实现http请求
@interface ViewController ()<NSURLSessionDataDelegate>//注意不是NSURLSessionDelegate或NSURLSessionTaskDelegate
@property(strong,nonatomic)NSMutableData *fileData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor redColor]];
}
- (NSMutableData *)fileData
{
if(!_fileData)
{
_fileData = [NSMutableData data];
}
return _fileData;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self httpWithDelegate];
}
- (void)httpWithDelegate
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/**
[NSURLSessionConfiguration defaultSessionConfiguration]
[NSURLSessionConfiguration ephemeralSessionConfiguration]
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier]
*/
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s",__func__);
/*
NSURLSessionResponseCancel = 0,
NSURLSessionResponseAllow = 1,
NSURLSessionResponseBecomeDownload = 2,
NSURLSessionResponseBecomeStream
*/
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"%s",__func__);
[self.fileData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s",__func__);
NSLog(@"%@",[[NSString alloc]initWithData:self.fileData encoding:NSUTF8StringEncoding]);
}
@end
NSURLSession(NSURLSessionDownloadTask)小文件下载
优点:无需担心内存
缺点:无法监听下载进度
- (void)download
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",location);
/*
location:
file:///Users/zhangfan/Library/Developer/CoreSimulator/Devices/DAB1A7AE-F373-4E79-8862-29433073DF3C/data/Containers/Data/Application/720AB0A4-5AC6-4024-8395-8FD9DAD60A9A/tmp/
*/
NSLog(@"%@",response);
NSLog(@"%@",error);
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@",fullPath);
//由于location所指向的是tmp路径,这里的文件是随时会被清理掉的,所以要把下载到的数据剪切到自己指定的路径
[[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
}];
[task resume];
}
NSURLSession(NSURLSessionDownloadTask)大文件下载(带断点续传)
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property(strong,nonatomic)NSURLSessionDownloadTask *task;
@property(strong,nonatomic)NSData *resumeData;
@property(strong,nonatomic)NSURLSession *session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor redColor]];
}
- (IBAction)startDownload:(id)sender {
[self bigDownloadWithDelegate];
}
- (IBAction)stopDownload:(id)sender {
//暂停是可以恢复的
[self.task suspend];
}
- (IBAction)cancelDownload:(id)sender {
//cancel是不能恢复的
//[self.task cancel];
//cancelByProducingResumeData是可以恢复的
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//恢复下载的数据并不等于文件数据
self.resumeData = resumeData;
}];
}
- (IBAction)resumeDownload:(id)sender {
if(self.resumeData)
{
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
}
[self.task resume];
}
- (void)bigDownloadWithDelegate
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
self.task = [self.session downloadTaskWithRequest:request];
[self.task resume];
}
/**
写数据时调用
参数:
session 会话对象
downloadTask 下载任务
bytesWritten 本次写入的数据大小
totalBytesWritten 已下载数据的大小
totalBytesExpectedToWrite 总数据大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
恢复下载的时候会调用
参数:
fileOffset 从什么地方下载
expectedTotalBytes 文件的总大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
/**
恢复下载的时候会调用
参数:
location 文件临时存储路径
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSLog(@"%@",fullPath);
//由于location所指向的是tmp路径,这里的文件是随时会被清理掉的,所以要把下载到的数据剪切到自己指定的路径
[[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
}
/**
请求结束
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
}
@end
支持App重新启动的断点续传
#import "ViewController.h"
#define fileName @"123123.mp4"
@interface ViewController ()<NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property(assign,nonatomic)NSInteger totalSize;
@property(assign,nonatomic)NSInteger currentSize;
@property(strong,nonatomic)NSFileHandle *handler;
@property(strong,nonatomic)NSURLSessionDataTask *task;
@property(strong,nonatomic)NSString *fullPath;
@property(strong,nonatomic)NSURLSession *session;
@end
@implementation ViewController
- (NSURLSessionDataTask *)task
{
if(_task == nil)
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
self.currentSize = [self getFileCurrentSize];
[self setProgress];
NSString *rangeString = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
[request setValue:rangeString forHTTPHeaderField:@"Range"];
_task = [self.session dataTaskWithRequest:request];
}
return _task;
}
- (NSURLSession *)session
{
if(_session == nil)
{
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (NSString *)fullPath
{
if(_fullPath == nil)
{
_fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileName];
}
return _fullPath;
}
- (NSInteger)getFileCurrentSize
{
//读取上次下载文件的当前大小
NSDictionary *dict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil];
NSInteger size = [dict[@"NSFileSize"] integerValue];
return size;
}
- (void)setProgress
{
float progress = 1.0 * self.currentSize / self.totalSize;
[self.progressView setProgress:progress];
[self.progressLabel setText:[NSString stringWithFormat:@"%d%%",(int)(progress * 100)]];
}
- (IBAction)startDownload:(id)sender {
[self.task resume];
}
- (IBAction)stopDownload:(id)sender {
[self.task suspend];
}
- (IBAction)cancelDownload:(id)sender {
[self.task cancel];
self.task = nil;
}
- (IBAction)resumeDownload:(id)sender {
[self.task resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
self.totalSize = response.expectedContentLength + self.currentSize;
if(self.currentSize == 0)
{
[[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil];
}
self.handler = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];
completionHandler(NSURLSessionResponseAllow);
[self.handler seekToEndOfFile];
NSLog(@"%@",self.fullPath);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
self.currentSize += data.length;
[self setProgress];
[self.handler writeData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"下载完成");
[self.handler closeFile];
self.handler = nil;
}
@end
NSURLSession上传
#import "ViewController.h"
// ----WebKitFormBoundaryvMI3CAV0sGUtL8tr
#define Kboundary @"----WebKitFormBoundaryjv0UfA04ED44AhWx"
#define KNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
@interface ViewController ()<NSURLSessionDataDelegate>
/** 注释 */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
-(NSURLSession *)session
{
if (_session == nil) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//是否运行蜂窝访问
config.allowsCellularAccess = YES;
config.timeoutIntervalForRequest = 15;
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self upload2];
}
//方法一
-(void)upload
{
//1.url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1 设置请求方法
request.HTTPMethod = @"POST";
//2.2 设请求头信息
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary] forHTTPHeaderField:@"Content-Type"];
//3.创建会话对象
// NSURLSession *session = [NSURLSession sharedSession];
//4.创建上传TASK
/*
第一个参数:请求对象
第二个参数:传递是要上传的数据(请求体)
第三个参数:
*/
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:[self getBodyData] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//6.解析
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//5.执行Task
[uploadTask resume];
}
//方法二
-(void)upload2
{
//1.url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1 设置请求方法
request.HTTPMethod = @"POST";
//2.2 设请求头信息
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary] forHTTPHeaderField:@"Content-Type"];
//3.创建会话对象
//4.创建上传TASK
/*
第一个参数:请求对象
第二个参数:传递是要上传的数据(请求体)
*/
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:[self getBodyData] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//6.解析
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//5.执行Task
[uploadTask resume];
}
-(NSData *)getBodyData
{
NSMutableData *fileData = [NSMutableData data];
//5.1 文件参数
/*
--分隔符
Content-Disposition: form-data; name="file"; filename="Snip20160225_341.png"
Content-Type: image/png(MIMEType:大类型/小类型)
空行
文件参数
*/
[fileData appendData:[[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
//name:file 服务器规定的参数
//filename:Snip20160225_341.png 文件保存到服务器上面的名称
//Content-Type:文件的类型
[fileData appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"Sss.png\"" dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
[fileData appendData:[@"Content-Type: image/png" dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
[fileData appendData:KNewLine];
UIImage *image = [UIImage imageNamed:@"Snip20160226_90"];
//UIImage --->NSData
NSData *imageData = UIImagePNGRepresentation(image);
[fileData appendData:imageData];
[fileData appendData:KNewLine];
//5.2 非文件参数
/*
--分隔符
Content-Disposition: form-data; name="username"
空行
123456
*/
[fileData appendData:[[NSString stringWithFormat:@"--%@",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
[fileData appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
[fileData appendData:KNewLine];
[fileData appendData:[@"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[fileData appendData:KNewLine];
//5.3 结尾标识
/*
--分隔符--
*/
[fileData appendData:[[NSString stringWithFormat:@"--%@--",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
return fileData;
}
#pragma mark ----------------------
#pragma mark NSURLSessionDataDelegate
/*
* @param bytesSent 本次发送的数据
* @param totalBytesSent 上传完成的数据大小
* @param totalBytesExpectedToSend 文件的总大小
*/
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
NSLog(@"%f",1.0 *totalBytesSent / totalBytesExpectedToSend);
}
@end
关于NSURLSessionConfiguration相关
- 作用:可以统一配置NSURLSession,如请求超时等
- 创建的方式和使用
//创建配置的三种方式
+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);
//统一配置NSURLSession
-(NSURLSession *)session
{
if (_session == nil) {
//创建NSURLSessionConfiguration
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//设置请求超时为10秒钟
config.timeoutIntervalForRequest = 10;
//在蜂窝网络情况下是否继续请求(上传或下载)
config.allowsCellularAccess = NO;
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
NSURLSession的对象在不用的时候需要做释放处理
使用
[self.session invalidateAndCancel];
或
[self.session finishTasksAndInvalidate];
否则应用会有内存泄露的问题