网络请求 NSURLsession(get、post、下载、上传)

本文详细介绍了iOS中NSURLSession的使用方法,包括GET和POST请求、文件下载及上传等操作,并提供了使用普通方式和代理方式的具体实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NSURLSession的简单介绍

  • ios9.0开始,NSURLConnection过期,NSURLSession的推出,早就是为了取代NSURLConnection
  • 使用步骤:使用NSURLSession对象创建Task,然后执行Task
  • Task的类型

普通方式

  • 使用系统创建的NSURLSession对象

使用NSURLSession发送GET请求(普通方式)

  1. - (void)get
    {

       // 获得NSURLSession对象

    NSURLSession *session = [NSURLSession sharedSession];

       // 创建任务

    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/login?username=123&pwd=4324"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

           NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
       }];
     
       // 启动任务
       [task resume];
    }

使用NSURLSession发送POST请求(普通方式)

  1. - (void)post
    {
       // 获得NSURLSession对象NSURLSession *session = [NSURLSession sharedSession];
     
       // 创建请求NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/login"]];
       request.HTTPMethod = @"POST"; // 请求方法

       request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding]; // 请求体

    // 创建任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

           NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
       }];
     
       // 启动任务
       [task resume];
    }

使用NSURLSession下载文件(普通方式)

  • 可以用来下载大文件,它内部是一点一点将文件下载到沙盒的tmp文件夹
  • 服务器响应完成后,只要将下载到tmp的文件剪切到caches文件夹,便可完成文件的下载
  • 缺点:不能监控下载进度(后面采用代理的方式解决)
  1. - (void)download
    {

       // 获得NSURLSession对象

    NSURLSession *session = [NSURLSession sharedSession];

     

       // 获得下载任务

    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://www.baidu.com/resources/videos/01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

     

        // 文件将来存放的真实路径

    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

     
         // 剪切location的临时文件到真实路径NSFileManager *mgr = [NSFileManager defaultManager];
           [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
       }];
     
       // 启动任务
       [task resume];
    }

代理方式

使用NSURLSession发送GET请求(代理方式)

  • NSURLSession对象需要自定义
  • 遵守协议NSURLSessionDataDelegate,实现相应的代理方法
  1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

       // 获得NSURLSession对象

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

     

       // 创建任务

    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/login?username=123&pwd=4324"]]];

     
       // 启动任务
       [task resume];
    }

  1. #pragma mark - <NSURLSessionDataDelegate>// 1.接收到服务器的响应
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
    {
       // 允许处理服务器的响应,才会继续接收服务器返回的数据
       completionHandler(NSURLSessionResponseAllow);
    }
     
     
    // 2.接收到服务器的数据(可能会被调用多次)
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
    {
       NSLog(@"%s", __func__);
    }
     
     
    // 3.请求成功或者失败(如果失败,error有值)
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
       NSLog(@"%s", __func__);
    }

使用NSURLSession发送POST请求(代理方式)

  • 实现方法跟GET请求一样,只是需要设置请求头

使用NSURLSession实现大文件(代理方式)

  • 可以监控下载进度
  • 但不能实现断点下载
  • 遵守协议NSURLSessionDownloadDelegate,实现相应的代理方法
  1. - (void)download
    {
       // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
     
       // 获得下载任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://www.baidu.com/resources/01.mp4"]];
     
       // 启动任务
       [task resume];
    }

  1. #pragma mark - <NSURLSessionDownloadDelegate>
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
       NSLog(@"didCompleteWithError");
    }
     
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
    {
       NSLog(@"didResumeAtOffset");
    }
     
    /**
    * 每当写入数据到临时文件时,就会调用一次这个方法
    * totalBytesExpectedToWrite:总大小
    * totalBytesWritten: 已经写入的大小
    * bytesWritten: 这次写入多少
    */
    - (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);
    }
     
    // 下载完毕就会调用一次这个方法
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
    {

       // 文件将来存放的真实路径

    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

     

       // 剪切location的临时文件到真实路径

    NSFileManager *mgr = [NSFileManager defaultManager];

       [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }

配置自定义NSURLSession对象

  • 一旦配置了,对所有使用NSURLSession创建的任务都有效
  1. - (NSURLSession *)session
    {
       if (!_session) {
           NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
     
           // 设置超时时长
           cfg.timeoutIntervalForRequest = 10;
     
           // 是否允许使用蜂窝网络(手机自带网络)
           cfg.allowsCellularAccess = YES;
           _session = [NSURLSession sessionWithConfiguration:cfg];
       }
       return _session;
    }

使用NSURLSession上传文件

  • 使用NSURLSession下载文件,确实比NSURLConnection简单,但使用NSURLSession下载文件,并没有改进
  • 一般上传文件建议使用第三方框架AFNetworking
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值