iOS Developer程序员

(IOS)如何处理不受信任的http网路凭证 (WebView,

2017-06-06  本文已影响708人  JamesDouble

本篇使用Swift 并附上官方文档

前阵子接了(公司A)一个专案,再加上要毕业了,学校各种忙碌,距离上一篇文章也有好大一段时间...,也是因为这个专案碰到了些小问题,才想来写写笔记。

一、起因

公司A有个只限内网用的公文系统(似乎是用java写的网页?),到目前为止都是单纯在Windows上的小程式利用『URL Scheme』跟这个系统互相丢接资料,我则是要负责写一个IOS App 跟此系统做一样的事。但我是承包的,无法在公司A的内网下测试,经过一番讨论,他们决定将系统做个测试用的灌在windows虚拟机上,我在Mac上执行就等于我跟这个系统相同内网。

二、前置测试 🖥️

假设各个内网ip如下:

(A)Mac:192.168.1.1

(B)Mac上的Windows虚拟机:192.168.1.2

(C)实机Iphone:192.168.1.3

(D)系统网址:https://192.168.1.2:8888/Domain

A ping B,C -> OK 👌、 B ping A,C -> OK 👌

A 预览 D -> OK 👌、 B 预览 D -> OK 👌

接下来让我们看看我要说的 C 预览 D 的状况

三、问题一 (UIWebView 预览 D) 🤔

三、问题一解法📖


       func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
  {
          LastRequest = request
          return true
  }
      
       func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
  {
          FailRequest = LastRequest
          if(FailRequest != nil)
          {
              let _:NSURLConnection = NSURLConnection(request: FailRequest! , delegate: self)!
          }
  }
      ```
      
*   虽然刚刚讲的是URLSession,但两个用法其实是相同的,所以我们遵守NSURLConnectionDelegate,并在最后重新Loading一次Request,这样同个Request就可以通了。
      
  ```swift
      func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge)
      {
          if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust  {
          print("send credential Server Trust")
          let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
          challenge.sender!.use(credential, for: challenge)
      }
      else{
          challenge.sender!.performDefaultHandling!(for: challenge)
      }
          connection.cancel()
          SystemWebView.loadRequest(FailRequest!)
  }
  ```
上一篇 下一篇

猜你喜欢

热点阅读