2017-03-21 22 views
1

我正在使用swift 3並首次訪問Web服務。我的Web服務通過HTTPS運行,我想用適當的加密進行測試。此服務器的證書對於swift 3上的自簽名證書無效3

這裏是我到目前爲止的代碼:

let config = URLSessionConfiguration.default // Session Configuration 
    let session = URLSession(configuration: config) // Load configuration into Session 
    let url = URL(string: webService.getLoginUrl())! 

    let task = session.dataTask(with: url, completionHandler: { 
     (data, response, error) in 

     if error == nil { 
      do { 
       if let json = 
        try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{ 
        //Implement your logic 
        print(json) 
       } 
      } catch { 
       print("error in JSONSerialization") 
      } 
     } else { 
      print(error!.localizedDescription) 
     } 

    }) 
    task.resume() 

當我跑這對我的測試服務器,這是自簽名,我得到:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be 「10.0.0.51」 which could put your confidential information at risk. 

所以我想要做什麼在測試時接受所有證書,但不在生產中。

我發現一對夫婦像網站:

http://www.byteblocks.com/Post/Use-self-signed-SSL-certificate-in-iOS-application https://github.com/socketio/socket.io-client-swift/issues/326

但這些似乎早SWIFT 3

我該如何解決這個問題?

回答

2

經過大量的研究,我瞭解了代表如何與SWIFT 3.太多件URLSession對象的工作來發布鏈接,但到了最後,這是最有幫助的:https://gist.github.com/stinger/420107a71a02995c312036eb7919e9f9

因此,修復問題,我繼承了我的URLSessionDelegate類,然後添加以下功能:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { 

    //accept all certs when testing, perform default handling otherwise 
    if webService.isTesting() { 
     print("Accepting cert as always") 
     completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!)) 
    } 
    else { 
     print("Using default handling") 
     completionHandler(.performDefaultHandling, URLCredential(trust: challenge.protectionSpace.serverTrust!)) 
    } 
} 

的isTesting()調用確定如果我使用的測試服務器,然後我們接受所有證書,如果我們在測試模式。

+0

什麼是webService? – Kingalione