Swift 3连接到具有XML无效证书的服务器

问题描述:

我在连接到服务器时遇到了一些问题。我只想发送用户名和密码,并从XML文件中获取一些数据。Swift 3连接到具有XML无效证书的服务器

let loginString = String(format: "%@:%@", username, password) 
    let loginData = loginString.data(using: String.Encoding.utf8)! 
    let base64LoginString = loginData.base64EncodedString() 

    let baseUrl = "xxxxxx" 
    let request = NSMutableURLRequest(url: NSURL(string: baseUrl)! as URL) 
    request.httpMethod = "POST" 
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") 
    let session = URLSession.shared 
    request.httpMethod = "GET" 

    var err: NSError? 

    let task = session.dataTask(with: request as URLRequest) { 
     (data, response, error) in 

     if data == nil { 
      print("dataTaskWithRequest error: \(error)") 
      return 
     } 

     let xml = SWXMLHash.parse(data!) 
     print(xml["mobile_devices"]["mobile_device"]["serial_number"].element?.text) 

     DispatchQueue.main.async(execute: { 
      // use main thread for UI updates 
     }) 

    } 
    task.resume() 

当我运行它,我得到以下错误(S):

nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9812] 2017-05-04 08:20:45.311 xxxx[23410:4428038] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) dataTaskWithRequest error: Optional(Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xxxxxxx” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=("cert(0x7f88d8834000) s: xxxxxxx JSS Built-in Certificate Authority>",

我从来没有真正做过与API和任何东西,所以我的学习,我去。以前,我不得不编辑plist文件以允许连接,并解决了我之前遇到的问题。我有这么远,但我不知道如何克服它。

我看到这一点:Connect to a Server with Invalid Certificate using NSURLSession (swift2,xcode7,ios9) 但它打破了我的代码

let session = URLSession.shared 

线。

我已经看到了这个为好,但我不能确定如何使用它:

Swift: How to request a URL with a self-signed certificate?

好。我找到了适合自己情况的解决方案。我贴在这里:Swift 3 NSURLSession/NSURLConnection HTTP load failed when connecting to a site with authentication

注意:这是一个安全问题,所以请不要这样做