大家好,我的开源项目PakePlus可以将网页/Vue/React项目打包为桌面/手机应用并且小于5M只需几分钟,官网地址:pakeplus.com

这个错误是 SSL 证书验证失败 导致的(code=-1202 对应 NSURLErrorServerCertificateUntrusted),因为你的服务端 https://192.168.31.197:5173/ 使用的是自签名证书或未被 iOS 信任的证书。以下是完整的解决方案,包含证书信任配置和 WKWebView 正确实现:
在 Info.plist 中添加以下配置:
Swift
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
或者更精确的配置:
Swift
<!-- 允许非HTTPS请求(可选,若服务端后续可能切换HTTP) -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<!-- 单独允许目标IP的HTTPS请求(更安全的写法) -->
<key>NSExceptionDomains</key>
<dict>
<key>192.168.31.197</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
</dict>
</dict>
</dict>
<!-- iOS 14+ 要求:允许加载本地网络资源 -->
<key>NSLocalNetworkUsageDescription</key>
<string>需要访问本地网络以加载服务端内容</string>
实现 WKWebView 并忽略 SSL 证书验证
WKWebView 默认严格验证 SSL 证书,需要通过 WKNavigationDelegate 手动忽略验证(仅用于开发环境,生产环境需使用正规证书):
Swift
class Coordinator: NSObject, WKNavigationDelegate {
let parent: WebView
init(_ parent: WebView) {
self.parent = parent
}
// 关键:强制信任所有SSL证书(仅开发环境!)
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// 1. 检查是否是服务器信任验证
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust else {
completionHandler(.performDefaultHandling, nil)
return
}
// 2. 获取服务器信任对象
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// 3. 强制信任证书(关键:忽略证书有效性检查)
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
// 调试:打印证书信息,确认是否是目标服务器
print("强制信任证书:\(challenge.protectionSpace.host):\(challenge.protectionSpace.port ?? 0)")
}
// 加载失败时打印详细错误(方便排查)
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
let nsError = error as NSError
print("加载失败:")
print("错误码:\(nsError.code)")
print("错误描述:\(nsError.localizedDescription)")
print("错误域名:\(nsError.domain)")
if let failureReason = nsError.localizedFailureReason {
print("失败原因:\(failureReason)")
}
}
}
大家好,我是1024小神,技术群 / 私活群 / 股票群 或 交朋友 都可以私信我。 如果你觉得本文有用,一键三连 (点赞、评论、关注),就是对我最大的支持~