swift中的这个函数适用于使用http://的网址,但不适用于使用https://的网址。我不确定错误是什么。我正在运行一个本地nodejs express服务器,它使用ssl证书接受https请求,但是swift客户端没有正确调用请求,如何在swift 3中将此代码更新为POST到https urls
注意:node.js服务器工作正常,我可以通过HTTPS从邮递员成功发送,是否有某种特殊配置需要在ios端完成才能发送https请求?
这是我从xcode控制台收到的错误消息
2017-10-05 08:17:10.991163-0700 HTTPS Requests[43803:3042492] []
nw_coretls_callback_handshake_message_block_invoke_3
tls_handshake_continue: [-9812]
2017-10-05 08:17:10.991 HTTPS Requests[43803:3042494]
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL,
-9813)
error in web request
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 “localhost” which could put your confidential
information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=
<SecTrustRef: 0x6180001273a0>, NSLocalizedRecoverySuggestion=Would you
like to connect to the server anyway?, _kCFStreamErrorDomainKey=3,
_kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=(
"<cert(0x7fe4ca810e00) s: localhost i: localhost>"
), NSUnderlyingError=0x6100000462a0 {Error
Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo=
{_kCFStreamPropertySSLClientCertificateState=0,
kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x6180001273a0>,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9813,
_kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813,
kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fe4ca810e00) s: localhost i: localhost>"
)}}, NSLocalizedDescription=The certificate for this server is invalid.
You might be connecting to a server that is pretending to be
“localhost” which could put your confidential information at risk.,
NSErrorFailingURLKey=https://localhost:8443/foo,
NSErrorFailingURLStringKey=https://localhost:8443/foo,
NSErrorClientCertificateStateKey=0})
func sendWebRequest(reqUrl: String, params: String, completionCallback:
@escaping ( [String: Any] )->())
{
let session = URLSession.shared
let url: URL = URL(string: reqUrl)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
//request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let paramString = params
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request)
{ data, response, error in
if error != nil
{
print("error in web request")
print(error.debugDescription)
}
else
{
DispatchQueue.main.async
{
/*need to dispatch this to main queue since this is in closure, so needs to update ui so needs to run on the main thread*/
if let data2 = data
{
//create json object from data
if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
{
completionCallback(json!)
}
}
}
}
}//completion handler end
task.resume() //start the web reuqest
}