我在連接到服務器時遇到了一些問題。我只想發送用戶名和密碼,並從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?