无法使用Alamofire连接到自签名本地主机服务器

时间:2018-07-11 21:43:51

标签: ios swift ssl alamofire

我正在创建一个与同一台计算机上托管的基本Web服务挂钩的应用程序,但一直无法克服此SSL错误。在Stack Overflow上存在一些与此相关的问题,但是如您在下面的代码中所见,我一直无法使这些解决方案起作用:

let sessionManager: SessionManager = {
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "https://localhost:5001": .disableEvaluation
    ]

    return SessionManager(
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
}()

class DataGetter {

    open class MyServerTrustPolicyManager: ServerTrustPolicyManager {
        open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
            return ServerTrustPolicy.disableEvaluation
        }
    }

    let sessionManager = SessionManager(delegate:SessionDelegate(), serverTrustPolicyManager:MyServerTrustPolicyManager(policies: [:]))

    func getSessionData(sessionId: Int) -> SessionAttendance {

        let session = SessionAttendance()
        let requestUrl = "https://localhost:5001/api/todo/" + String(sessionId)
        Alamofire.request(requestUrl, method: .get).validate().responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                print("JSON: \(json)")
            case .failure(let error):
                print(error)
            }
        }
        return session
    }
}

当我尝试运行 getSessionData 方法时,出现以下错误:

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."

我尝试启用 NSAllowsLocalNetworking,NSAllowsArbitraryLoads ,并在info.plist中的“例外域”下添加了“ localhost”。我还从钥匙串中导出了.cer证书,并将其安装到模拟器中。正如您在上面的代码中看到的那样,我已经在其他问题中尝试了Alamofire的变通方法。这些解决方案均无效。

有人知道如何解决此错误,以便我可以从本地Web服务接收数据吗?谢谢。

编辑:我的info.plist文件的一部分

key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsLocalNetworking</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.2</string>
            </dict>
        </dict>
    </dict>

0 个答案:

没有答案