当前位置: 移动技术网 > 移动技术>移动开发>IOS > IOS UIWebView获取404、504等错误问题解决方案

IOS UIWebView获取404、504等错误问题解决方案

2019年07月24日  | 移动技术网移动技术  | 我要评论
uiwebview获取404、504等错误码 问题描述     在使用webview时,会存在这么一个问题:

uiwebview获取404、504等错误码

问题描述

    在使用webview时,会存在这么一个问题:
    如果访问服务器返回异常,比如404、504这样的错误,需要在native端展示特定的图片和文案(404、504酱紫的错误码有些不美观)。那么,问题就来了,怎样才能知道webview的访问出错了,是什么错???

问题分析

    从webview发起请求之后,能够查看webview加载状态的就是它的代理了,所以就从各个代理方法着手分析。

 // webview被指示加载内容时调用,返回yes才会进行加载
  - (bool)webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype;
  // webview已经开始加载一个请求后调用
  - (void)webviewdidstartload:(uiwebview *)webview;
  // webview结束加载请求之后调用
  - (void)webviewdidfinishload:(uiwebview *)webview;
  // 请求加载中发生错误时调用
  - (void)webview:(uiwebview *)webview didfailloadwitherror:(nullable nserror *)error;

    首先,肯定是从didfailloadwitherror代理方法入手,发现请求到404页面时,并没有调用该方法,这是为什么呢?原来,该方法时加载过程出现问题调用,我们顺利的得到了404页面,就不算加载过程的问题。

    然后,从网上搜索该问题,发现网友提供的方法都是使用sendsynchronousrequest方法返回nshttpurlresponse的状态码进行判断。可是,又出现了一个警告,sendsynchronousrequest在ios9以后被弃用了,就用新的方法datataskwithrequest代理。

 'sendsynchronousrequest:returningresponse:error:' is deprecated: first deprecated in ios 9.0 - use [nsurlsession datataskwithrequest:completionhandler:]

    以上是获取状态码的方式,具体在哪个代理函数中处理,还得再看看:

    通过具体代码分析发现,放在shouldstartloadwithrequest和webviewdid finishload都可以得到相应的状态码,放在webviewdidstartload得到的状态码都是0.经过分析发现,调用webviewdidstartload方法时,request请求已经发起正在等待服务器处理结果。

问题解决

    综上,最终该问题就有两种处理方式了,分别是sendsynchronousrequest和datataskwithrequest。具体代码如下:

 // 方法一
  nshttpurlresponse *response = nil;
  [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:nil];
  nslog(@"statuscode:%ld", response.statuscode);
   // 方法二
  nsurlsessiondatatask * datatask = [[nsurlsession sharedsession] datataskwithrequest:webview.request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
    nshttpurlresponse *tmpresponse = (nshttpurlresponse*)response;
    nslog(@"statuscode:%ld", tmpresponse.statuscode);
  }];
  [datatask resume];

    在shouldstartloadwithrequest和webviewdidfinishload方法中都能获取到该状态码,具体可以根据业务需求确定。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网