IOS开发基础之NSURLSession的使用

该博客介绍了iOS开发中使用NSURLSession进行网络请求的基础操作,包括dataTask的使用来发送POST和GET请求,以及downloadTask的使用进行文件下载,并展示了如何处理下载进度。通过实例代码详细阐述了NSURLSession在数据传输和断点续传中的应用。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值