在Swift 5中无法调用https请求(自签名证书)

时间:2019-07-22 18:15:23

标签: node.js swift api nginx swift5

我无法将请求发送到https API。 您可以访问https://13.48.109.132/api并可以查看快递网站。 我使用Nginx,您可以在此处检查配置。另外,我现在仅使用IP地址,而不使用域名。如您在此处的Nginx配置中所见,在调用https://13.48.109.132/api之后,我调用了由pm2(Http,9000端口)托管的Node.js服务器。当我在网络浏览器中致电时,我意识到它正在工作。

location /api/ {
        proxy_pass http://localhost:9000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

但是我无法在Swift 5中调用此api。

var jsonResponse: Dictionary<String, String> = [:]
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
            do {
                if data != nil {
                    jsonResponse = try JSONSerialization.jsonObject(with: data!) as! [String: String]
                    taskCallback(true, jsonResponse as Dictionary<String, String>?)
                } else {
                    taskCallback(false, jsonResponse as Dictionary<String, String>?)
                }

            } catch {
                taskCallback(false, jsonResponse as Dictionary<String, String>?)
            }
        })
        task.resume()

我可以看到以下错误。

2019-07-23 00:47:25.957170+0800 Marvel[2464:869140] TIC SSL Trust Error [1:0x281f2e4c0]: 3:0
2019-07-23 00:47:25.984462+0800 Marvel[2464:869140] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2019-07-23 00:47:25.984575+0800 Marvel[2464:869140] Task <AEBD09B5-023E-448D-8233-BFAC0A68B682>.<1> HTTP load failed (error code: -1202 [3:-9813])
2019-07-23 00:47:25.985082+0800 Marvel[2464:869205] Task <AEBD09B5-023E-448D-8233-BFAC0A68B682>.<1> finished with error - code: -1202
response Optional([:])

我检查stackoverflow文章并找到像这样的info.plist配置

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

但是它不起作用。 希望您的帮助。

1 个答案:

答案 0 :(得分:0)

此行不正确

LauchScreen.storyboard

您应该设置一个网址

var request = URLRequest(url: URL(string: url)!)