网络编程归纳总结八阶段
NSURLSession
之前发送网络请求的过程
URL — URLRequest—URLConnection
NSURLSession—-iOS7.0以后
用于替代NSURLConnection
支持后台运行的网络任务
暂停、停止、重启网络任务,不再需要自己封装NSOperation
下载、断点续传、异步下载
上传、异步上传
获取下载、上传的进度
NSURLSession可以发起以下任务,默认所有的任务都是挂起的
DataTask UploadTask
DownloadTask
NSURLSessionConfigration
配置请求的信息
DataTask
启动任务–执行的过程是异步的
//发送get请求
- (void)dataTask1:(NSString *)urlString{
//创建url
NSURL *url = [NSURL URLWithString:urlString];
//单例的方法获取session对象
NSURLSession *session = [NSURLSession sharedSession];
//通过session获取一个dataTask,默认任务都是挂起状态
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@ --- %@",result, [NSThread currentThread]);
}];
//启动任务
[dataTask resume];
NSLog(@"over");
}
//代码精简
- (void)dataTask2:(NSString *)urlString{
//创建url
NSURL *url = [NSURL URLWithString:urlString];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@ --- %@",result, [NSThread currentThread]);
}] resume];
}
DownloadTask
下载DownloadTask
默认把文件下载到沙盒的tmp文件夹
下载完成后不会文件做任何操作,会自动删除文件
下载过程是异步的
//代码示例:
- (void)downloadTask:(NSString *)str{
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:str];
[[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
//下载完成后的文件路径
NSLog(@"%@",location);
//下载的文件在tmp文件夹中,转瞬即逝
//把下载的文件保存到caches目录下
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"123.mp4"];
[[NSFileManager defaultManager] copyItemAtPath:location.path toPath:path error:NULL];
}] resume];
}
下载进度
跟踪下载进度,跟之前类似,使用NSURLSession的代理方法
跟踪下载进度,不能使用sharedSession,全局的,不能设置代理需要新建一个NSURLSession
使用的代理NSURLSessionDownloadDelegate
NSURLSessionDownloadDelegate—>NSURLSessionTaskDelegate–>NSURLSessionDelegate
创建session对象
//懒加载,创建session对象
- (NSURLSession *)session{
if (_session == nil) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue new]];
}
return _session;
}
//调用,创建下载任务,调用代理跟之前不一样
NSURL *url = [NSURL URLWithString:str];
[[self.session downloadTaskWithURL:url] resume];
downloadTask的代理方法
#pragma mark - session的代理方法
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"%@",location);
}
//断点续传
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"====");
}
//下载进度
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
//bytesWritten 本次下载的字节
//totalBytesWritten 总共下载的字节
//totalBytesExpectedToWrite 文件的大小 字节
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"%f",progress);
}
断点续传
在界面上放三个按钮,开始、暂停、继续
开始–记录下下载的任务
NSURL *url = [NSURL URLWithString:urlStr];
self.downloadTask = [self.session downloadTaskWithURL:url];
[self.downloadTask resume];
暂停–记录暂停的数据
[self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
//暂停要 存储当前数据
[self.resumeData writeToFile:self.path atomically:YES];
}];
self.downloadTask = nil;
继续–使用续传数据继续下载任务,记录下载任务为下一次暂停使用
//续传,先加载暂停的数据
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:self.path]) {
//如果文件存在
self.resumeData = [NSData dataWithContentsOfFile:self.path];
}
if (self.resumeData == nil) {
return;
}
//继续下载
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData ];
[self.downloadTask resume];
self.resumeData = nil;
使用progressView显示下载进度
断点续传保存到文件。每次重新运行应用的时候都会重新创建沙盒。重新生成一个bundleID
其它
在界面上放一个scrollView拖动的时候,下载任务不会停止
原因:
下载任务是异步执行的(即使把下载任务添加到主队列中)
当发生合适的事件后,通知代理对象
所有的代理方法都是在主线程上异步执行的(任务添加到主队列的时候)
拖动scrollView的时候下载不会停止
创建session的时候,队列设置为nil,和写[[NSOperationQueue alloc] init]的效果是一样的
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
队列的选择
如果下载完成后更新主界面使用主队列
如果下载完成后执行后续操作。使用新队列
压缩和解压缩
压缩和解压使用第三方框架ssziparchive
底层是c语言的,调用封装好的类
导入ssziparchive
编译报错,要导入动态库libz
//解压
[SSZipArchive unzipFileAtPath:location.path toDestination:dir];
- (void)downloadTask:(NSString *)str{
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:str];
[[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
//下载完成后的文件路径
NSLog(@"%@",location);
//下载完压缩包后解压
NSString *dir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
[SSZipArchive unzipFileAtPath:location.path toDestination:dir];
}] resume];
}
最近才开始往github上放东西 在公司写的又不能放= = 大家姑且看看吧
github地址: https://github.com/FuThD