当前位置: 移动技术网 > 移动技术>移动开发>IOS > IOS网络请求之NSURLSession使用详解

IOS网络请求之NSURLSession使用详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

前言:

无论是android还是ios都离不开与服务器交互,这就必须用到网络请求,记得在2013年做ios的时候那时候用的asihttprequest框架,现在重新捡起ios的时候asihttprequest已经停止维护,大家都在用afnetworking作为首选网络请求框架,之前的asihttprequest是基于nsurlconnection类实现的,早期的afnetworking也是基于nsurlconnection实现,后来ios9 之后已经放弃了nsurlconnection,开始使用ios 7之后推出的nsurlsession,本着追根溯源的原则,首先学习一下nsurlsession的实现网络请求,然后再去学习afnetworking。

了解nsurlsession

nsurlsession是2013年ios 7发布的用于替代nsurlconnection的,ios 9之后nsurlconnection彻底推出历史舞台。其使用起来非常方便,今天使用nsurlconnection分别实现了get、post、表单提交、文件上传、文件下载,让我这个以android开发为主的屌丝程序员赞叹不已,根据nsurlsession会话对象创建一个请求task,然后执行该task即可,包括缓存、会话周期,多线程任务ios都已经在sdk层面封装完毕,不过比较遗憾的时nsurlsession只提供了异步请求方式而没有提供同步请求方式。接下来我们来如何实现网络请求。

nsurlsession使用

我们首先以一个简单的get请求为例开始。

1.)首先构造一个nsurl请求资源地址

  // 构造url资源地址
  nsurl *url = [nsurl urlwithstring:@http://api.nohttp.net/method?name=yanzhenjie&pwd=123];

2.)创建一个nsrequest请求对象

  // 创建request请求
  nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
  // 配置request请求
  // 设置请求方法
  [request sethttpmethod:@"get"];
  // 设置请求超时 默认超时时间60s
  [request settimeoutinterval:10.0];
  // 设置头部参数
  [request addvalue:@"gzip" forhttpheaderfield:@"content-encoding"];
  //或者下面这种方式 添加所有请求头信息
  request.allhttpheaderfields=@{@"content-encoding":@"gzip"};
  //设置缓存策略
  [request setcachepolicy:nsurlrequestreloadignoringlocalcachedata];

根据需求添加不用的设置,比如请求方式、超时时间、请求头信息,这里重点介绍下缓存策略:

  • nsurlrequestuseprotocolcachepolicy = 0 //默认的缓存策略, 如果缓存不存在,直接从服务端获取。如果缓存存在,会根据response中的cache-control字段判断下一步操作,如: cache-control字段为must-revalidata, 则询问服务端该数据是否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端.
  • nsurlrequestreloadignoringlocalcachedata = 1 //忽略本地缓存数据,直接请求服务端.
  • nsurlrequestignoringlocalandremotecachedata = 4 //忽略本地缓存,代理服务器以及其他中介,直接请求源服务端.
  • nsurlrequestreloadignoringcachedata = nsurlrequestreloadignoringlocalcachedata
  • nsurlrequestreturncachedataelseload = 2 //有缓存就使用,不管其有效性(即忽略cache-control字段), 无则请求服务端.
  •  nsurlrequestreturncachedatadontload = 3 //只加载本地缓存. 没有就失败. (确定当前无网络时使用)
  • nsurlrequestreloadrevalidatingcachedata = 5 //缓存数据必须得得到服务端确认有效才使用

3.)创建nsurlsession会话对象

可以通过采用ios共享session的方式

  // 采用苹果提供的共享session
  nsurlsession *sharedsession = [nsurlsession sharedsession];

可以通过nsurlsessionconfiguration方式配置不同的nsurlsession

  // 构造nsurlsessionconfiguration
  nsurlsessionconfiguration *configuration = [nsurlsessionconfiguration defaultsessionconfiguration];
  // 构造nsurlsession,网络会话;
  nsurlsession *session = [nsurlsession sessionwithconfiguration:configuration];

通过nsurlsessionconfiguration提供了三种创建nsurlsession的方式

  • defaultsessionconfiguration //默认配置使用的是持久化的硬盘缓存,存储证书到用户钥匙链。存储cookie到sharecookie。
  • ephemeralsessionconfiguration //不使用永久持存cookie、证书、缓存的配置,最佳优化数据传输。
  • backgroundsessionconfigurationwithidentifier //可以上传下载http和https的后台任务(程序在后台运行)。

在后台时,将网络传输交给系统的单独的一个进程,即使app挂起、推出甚至崩溃照样在后台执行。

也可以通过nsurlsessionconfiguration统一设置超时时间、请求头等信息

  // 构造nsurlsessionconfiguration
  nsurlsessionconfiguration *configuration = [nsurlsessionconfiguration defaultsessionconfiguration];
  //设置请求超时为10秒钟
  configuration.timeoutintervalforrequest = 10;
  
  //在蜂窝网络情况下是否继续请求(上传或下载)
  configuration.allowscellularaccess = no;

  //配置请求头
  configuration.httpadditionalheaders =@{@"content-encoding":@"gzip"};

4.) 创建nsurlsessiontask对象,然后执行

  // 构造nsurlsessiontask,会话任务;
  nsurlsessiondatatask *task = [session datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
    // 请求失败,打印错误信息
    if (error) {
      nslog(@"get error :%@",error.localizeddescription);
    }
    //请求成功,解析数据
    else {
      // json数据格式解析
      id object = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:&error];
      // 判断是否解析成功
      if (error) {
        nslog(@"get error :%@",error.localizeddescription);
      }else {
        nslog(@"get success :%@",object);
        // 解析成功,处理数据,通过gcd获取主队列,在主线程中刷新界面。
        dispatch_async(dispatch_get_main_queue(), ^{
          // 刷新界面....
        });
      }
    }
  }];

ios为了适应不同的应用场景提供了不同类型的nssessiontask

  • nsurlsessiondatatask  //一般的get、post等请求
  • nsurlsessionuploadtask // 用于上传文件或者数据量比较大的请求
  • nsurlsessiondownloadtask //用于下载文件或者数据量比较大的请求
  • nsurlsessionstreamtask //建立一个tcp / ip连接的主机名和端口或一个网络服务对象。

task的三个函数

  • - (void)suspend;//暂停
  • - (void)resume;//开始或者恢复
  • - (void)cancel;//关闭任务

nsurlsession其他请求示例

1.)post请求

  // 1、创建url资源地址
  nsurl *url = [nsurl urlwithstring:@"http://api.nohttp.net/postbody"];
  // 2、创建reuest请求
  nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
  // 3、配置request
  // 设置请求超时
  [request settimeoutinterval:10.0];
  // 设置请求方法
  [request sethttpmethod:@"post"];
  // 设置头部参数
  [request addvalue:@"gzip" forhttpheaderfield:@"content-encoding"];
  // 4、构造请求参数
  // 4.1、创建字典参数,将参数放入字典中,可防止程序员在主观意识上犯错误,即参数写错。
  nsdictionary *parametersdict = @{@"name":@"yanzhenjie",@"pwd":@"123"};
  // 4.2、遍历字典,以“key=value&”的方式创建参数字符串。
  nsmutablestring *parameterstring = [[nsmutablestring alloc]init];
  int pos =0;
  for (nsstring *key in parametersdict.allkeys) {
    // 拼接字符串
    [parameterstring appendformat:@"%@=%@", key, parametersdict[key]];
    if(pos<parametersdict.allkeys.count-1){
      [parameterstring appendstring:@"&"];
    }
    pos++;
  }
  // 4.3、nsstring转成nsdata数据类型。
  nsdata *parametersdata = [parameterstring datausingencoding:nsutf8stringencoding];
  // 5、设置请求报文
  [request sethttpbody:parametersdata];
  // 6、构造nsurlsessionconfiguration
  nsurlsessionconfiguration *configuration = [nsurlsessionconfiguration defaultsessionconfiguration];
  // 7、创建网络会话
  nsurlsession *session = [nsurlsession sessionwithconfiguration:configuration];
  // 8、创建会话任务
  nsurlsessiondatatask *task = [session datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
    // 10、判断是否请求成功
    if (error) {
      nslog(@"post error :%@",error.localizeddescription);
    }else {
      // 如果请求成功,则解析数据。
      id object = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:&error];
      // 11、判断是否解析成功
      if (error) {
        nslog(@"post error :%@",error.localizeddescription);
      }else {
        // 解析成功,处理数据,通过gcd获取主队列,在主线程中刷新界面。
        nslog(@"post success :%@",object);
        dispatch_async(dispatch_get_main_queue(), ^{
          // 刷新界面...
        });
      }
    }
    
  }];
  // 9、执行任务
  [task resume];

 2.)附带表单参数文件上传

  nsdate* dat = [nsdate datewithtimeintervalsincenow:0];
  nstimeinterval a=[dat timeintervalsince1970];
  nsstring* filename = [nsstring stringwithformat:@"file_%0.f.txt", a];
  
  [fileutils writedatatofile:filename data:[@"upload_file_to_server" datausingencoding:nsutf8stringencoding]];
  
  // 以流的方式上传,大小理论上不受限制,但应注意时间
  // 1、创建url资源地址
  nsurl *url = [nsurl urlwithstring:@"http://api.nohttp.net/upload"];
  // 2、创建reuest请求
  nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
  // 3、配置request
  //设置body值方法二,这种方法比较原始,不常用,不过可以用来上传参数和文件
  nsstring *boundary = @"whoislcj";//表单分界线 可以自定义任意值
  [request setvalue:[@"multipart/form-data; boundary=" stringbyappendingstring:boundary] forhttpheaderfield:@"content-type"];
  // 文件上传使用post
  [request sethttpmethod:@"post"];
  // 设置请求超时
  [request settimeoutinterval:30.0f];
  //用于存放二进制数据流
  nsmutabledata *body = [nsmutabledata data];
  
  //追加一个普通表单参数 name=yanzhenjie
  nsstring *nameparam = [nsstring stringwithformat:@"--%@\r\ncontent-disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",boundary,@"name",@"yanzhenjie",nil];
  [body appenddata:[nameparam datausingencoding:nsutf8stringencoding]];
  
  //追加一个普通表单参数 pwd=123
  nsstring *pwdparam = [nsstring stringwithformat:@"--%@\r\ncontent-disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",boundary,@"pwd",@"123",nil];
  [body appenddata:[pwdparam datausingencoding:nsutf8stringencoding]];
  
  //追加一个文件表单参数
  // content-disposition: form-data; name="<服务器端需要知道的名字>"; filename="<服务器端这个传上来的文件名>"
  // content-type: application/octet-stream --根据不同的文件类型选择不同的值
  nsstring *file = [nsstring stringwithformat:@"--%@\r\ncontent-disposition: form-data; name=\"%@\";filename=\"%@\"\r\ncontent-type: application/octet-stream\r\n\r\n",boundary,@"headurl",filename,nil];
  [body appenddata:[file datausingencoding:nsutf8stringencoding]];
  //获取file路径
  nsstring *filepath =[fileutils getfilepath:filename];
  nsdata *data =[nsdata datawithcontentsoffile:filepath];
  //追加文件二进制数据
  [body appenddata:data];
  [body appenddata:[@"\r\n" datausingencoding:nsutf8stringencoding]];
  //结束分割线
  nsstring *endstring = [nsstring stringwithformat:@"--%@--",boundary];
  [body appenddata:[endstring datausingencoding:nsutf8stringencoding]];
  
  // 创建会话
  nsurlsession *session = [nsurlsession sharedsession];
  // 3.开始上传  request的body data将被忽略,而由fromdata提供
  nsurlsessionuploadtask *uploadtask= [session uploadtaskwithrequest:request fromdata:body completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
    if (error) {
      nslog(@"upload error:%@",error);
    } else {
      nslog(@"upload success:%@", [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:&error]);
      dispatch_async(dispatch_get_main_queue(), ^{
        // 刷新界面...
      });
    }
  }];
  //执行任务
  [uploadtask resume];

 3.)文件下载

// 创建url
  nsstring *urlstr =@"http://images2015.cnblogs.com/blog/950883/201701/950883-20170105104233581-62069155.png";
  nsurl *url = [nsurl urlwithstring:urlstr];
  // 创建请求
  nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
  // 设置请求超时
  [request settimeoutinterval:30.0];
  // 创建会话
  nsurlsession *session = [nsurlsession sharedsession];
  
  nsurlsessiondownloadtask *downloadtask = [session downloadtaskwithrequest:request completionhandler:^(nsurl * _nullable location, nsurlresponse * _nullable response, nserror * _nullable error) {
    if (!error) {
      nslog(@"download sucess : %@", location);
      nsdata *data=[nsdata datawithcontentsofurl:location];
      uiimage *image=[uiimage imagewithdata:data];
      dispatch_async(dispatch_get_main_queue(), ^{
        // 刷新界面...
        uiimageview *imageview =[[uiimageview alloc]init];
        imageview.image=image;
        [self.view addsubview:imageview];
        [imageview mas_makeconstraints:^(masconstraintmaker *make) {
          make.center.equalto(self.view);
          make.size.mas_equalto(cgsizemake(300, 300));
        }];
      });
    } else {
      nslog(@"download error : %@", error.localizeddescription);
    }
  }];
  //启动任务
  [downloadtask resume];

总结:

今天学习了ios底层如何实现网络请求的,为了开发效率还得依靠优秀的第三方开源框架,以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网