iOS模拟器请求HTTPS服务器报证书无效[-1202]错误求助
Swift请求localhost HTTPS接口证书无效[-1202]问题解决
问题背景
在iPhone14模拟器中,使用Swift代码向https://localhost:8443/process_file发送POST请求时,出现证书无效的[-1202]错误,但Dart客户端和Postman测试该接口均正常。环境为Xcode 14.2、macOS 12.6.3。
错误核心提示:
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.
解决方案
1. 信任自定义CA证书(开发环境推荐)
若服务器使用自签名CA签发的证书,需让App主动信任该CA:
步骤1:导入CA证书到项目
将你的CA证书文件(如my-ca.cer)拖入Xcode项目,勾选对应App目标的"Add to targets"选项。
步骤2:配置URLSession信任策略
创建自定义URLSession,加载CA证书并完成服务器证书验证:
// 加载项目中的CA证书 func loadCACertificate() -> SecCertificate? { guard let certPath = Bundle.main.path(forResource: "my-ca", ofType: "cer"), let certData = try? Data(contentsOf: URL(fileURLWithPath: certPath)) else { return nil } return SecCertificateCreateWithData(nil, certData as CFData) } // 创建带信任验证的URLSession func createTrustedSession() -> URLSession { let config = URLSessionConfiguration.default return URLSession(configuration: config, delegate: self, delegateQueue: nil) } // 实现URLSessionDelegate的证书验证逻辑 extension YourClass: URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let serverTrust = challenge.protectionSpace.serverTrust, let caCert = loadCACertificate() else { completionHandler(.cancelAuthenticationChallenge, nil) return } // 将CA证书设为信任锚点 let trustAnchor = SecTrustAnchor(certificate: caCert) let trustPolicies = [SecTrustPolicyCreateAnchorCertificates([trustAnchor] as CFArray)] // 执行信任评估 var trustResult: SecTrustResultType = .invalid SecTrustSetPolicies(serverTrust, trustPolicies as CFArray) let status = SecTrustEvaluate(serverTrust, &trustResult) if status == errSecSuccess && (trustResult == .unspecified || trustResult == .proceed) { let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } else { completionHandler(.cancelAuthenticationChallenge, nil) } } } // 使用自定义Session发送请求 let session = createTrustedSession() let task = session.dataTask(with: request) { data, response, error in // 处理请求回调逻辑 } task.resume()
2. 临时绕过证书验证(仅开发环境,禁止生产使用)
如果只是开发阶段快速测试,可临时跳过证书验证,但绝对不能用于生产环境:
// 创建带代理的URLSession let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) // 实现URLSessionDelegate跳过验证 extension YourClass: URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) } else { completionHandler(.performDefaultHandling, nil) } } } // 发送请求 let task = session.dataTask(with: request) { data, response, error in // 处理回调 } task.resume()
3. 检查证书配置正确性
若上述方法无效,确认服务器证书是否符合要求:
- 证书的**Common Name(CN)必须为
localhost,或Subject Alternative Name(SAN)**列表包含localhost - 证书未过期
- 自定义CA证书已导入模拟器的系统信任列表(路径:模拟器设置→通用→关于本机→证书信任设置,开启对应CA的信任开关)
内容的提问来源于stack exchange,提问作者Tusshu
相关产品推荐
相关产品推荐

