iOS URLSession请求本地HTTPS接口时禁用证书校验解决SSL报错
本地调试HTTPS请求跳过SSL证书校验方案
注意:该方案仅适用于本地开发联调场景,生产环境严禁使用,否则会引发中间人攻击等数据安全风险,也可能导致App Store审核被拒。
实现步骤
- 让发起网络请求的类遵循
URLSessionDelegate协议,实现证书校验回调,支持自定义证书信任逻辑。如果只需要给本地localhost放开校验,可以在回调里增加域名判断,避免影响其他正式接口的安全校验:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // 仅对本地localhost域名放开证书校验 guard challenge.protectionSpace.host == "localhost", let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) }
- 替换原有代码中使用的
URLSession.shared单例,自定义初始化URLSession实例,将当前类设置为session的delegate,修改后的getUsers代码如下:
func getUsers() { guard let url = URL(string: "https://localhost:5001/Zona/User") else {return print("ERROR")} let urlRequest = URLRequest(url: url) // 自定义session,绑定delegate处理证书逻辑 let customSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil) let dataTask = customSession.dataTask(with: urlRequest) { (data, response, error) in if let error = error { print("Request error: ", error) return } guard let response = response as? HTTPURLResponse else { return } if response.statusCode == 200 { guard let data = data else { return } DispatchQueue.main.async { do { let decodedUsers = try JSONDecoder().decode([User].self, from: data) self.users = decodedUsers } catch let error { print("Error decoding: ", error) } } } } dataTask.resume() }
补充说明
- 原报错Code=-1202是iOS系统的默认安全策略:当HTTPS服务器使用的证书不是系统信任的根证书签发时(比如本地开发用的自签名证书),会主动拦截请求,避免用户连接到仿冒服务器。
- 调试结束后请及时移除自定义证书信任逻辑,切回默认的
URLSession.shared发起请求,保证线上请求的安全性。
内容的提问来源于stack exchange,提问作者danrom11
相关产品推荐
相关产品推荐

