IOS开发基础之NSURLSession的使用
服务器我们选用的是tomcat服务器。
所有项目info.plist加入
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
第一章:
- NSURLSession的使用演示之 dataTask 的使用 源码
// ViewController.m
// 25-Session的演示
// Created by 鲁军 on 2021/3/7.
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self dataTask3];
}
//发送post请求
-(void)dataTask3{
NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"post";
NSString *body = @"username=123&pwd=123";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",json);
}] resume];
}
//NSURLSession DataTask
//简化代码
-(void)dataTask2{
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",json);
}] resume];
}
-(void)dataTask1{
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",json);
}];
//开始任务
[dataTask resume];
}
@end
第二章:
- NSURLSession的使用演示之 downloadTask 的使用 下载进度的 源码
// ViewController.m
// 26- 下载进度
// Created by 鲁军 on 2021/3/7.
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property(nonatomic,strong)NSURLSession *session;
@end
@implementation ViewController
//懒加载
- (NSURLSession *)session{
if(_session==nil){
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session =[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self downloadTask];
}
-(void)downloadTask{
NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];
//如果设置成代理 不能使用回调。 否则代理的方法不执行
// [[self.session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// NSLog(@"%@",[NSThread currentThread]);
// NSLog(@"--下载完成 : %@",location);
//
//
// }] resume];
//在主线程执行的 文件是删除 的 ,需要的时候。需要自己保存
[[self.session downloadTaskWithURL:url] resume];
}
//代理方法
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"%@",[NSThread currentThread]);
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{
float process =totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
NSLog(@"下载进度 = %f",process);
}
@end
第三章
- 断点续传的综合案例的实现
// ViewController.m
// 27-断点续传
// Created by 鲁军 on 2021/3/7.
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property(nonatomic,strong)NSURLSession *session;
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;
@property(nonatomic,strong) NSData *resumeData;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@end
@implementation ViewController
//懒加载
- (NSURLSession *)session{
if(_session==nil){
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session =[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
//开始下载
- (IBAction)startClick:(id)sender {
[self download];
}
//暂停下载
- (IBAction)pauseClick:(id)sender {
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//保存续传的数据
self.resumeData = resumeData;
//把续传数据保存到沙盒容器中
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"456.tmp"];
[self.resumeData writeToFile:path atomically:YES];
self.downloadTask = nil;
NSLog(@"%@",resumeData);
}];
}
//继续下载
- (IBAction)resumeClick:(id)sender {
//从沙盒容器取文件
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"456.tmp"];
NSFileManager *fileManger =[NSFileManager defaultManager];
if([fileManger fileExistsAtPath:path]){
self.resumeData = [NSData dataWithContentsOfFile:path];
}
if(self.resumeData == nil){
return;
}
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
[self.downloadTask resume];
self.resumeData = nil;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
//开始下载
-(void)download{
NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];
NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithURL:url];
self.downloadTask = downloadTask;
[downloadTask resume];
}
//代理方法
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"%@",[NSThread currentThread]);
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{
float process =totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
NSLog(@"下载进度 = %f",process);
self.progressView.progress = process;
}
@end