swiftui使用WKWebView加载自签的https服务,允许不安全访问

大家好,我的开源项目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小神,技术群 / 私活群 / 股票群 或 交朋友 都可以私信我。 如果你觉得本文有用,一键三连 (点赞、评论、关注),就是对我最大的支持~

相关推荐
锋行天下15 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
1024肥宅16 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
海市公约17 小时前
HTML网页开发从入门到精通:从标签到表单的完整指南
前端·ide·vscode·程序人生·架构·前端框架·html
行云流水62617 小时前
前端树形结构实现勾选,半勾选,取消勾选。
前端·算法
diudiu_3318 小时前
web漏洞--认证缺陷
java·前端·网络
阿珊和她的猫18 小时前
<video>` 和 `<audio>` 标签的常用属性解析
前端
LSL666_18 小时前
4 jQuery、JavaScript 作用域、闭包与 DOM 事件绑定
前端·javascript·html
yinuo19 小时前
前端跨页面通讯终极指南⑤:window.name 用法全解析
前端
小飞侠在吗19 小时前
vue computed 和 watch
前端·javascript·vue.js
yinuo19 小时前
前端跨页面通讯终极指南④:MessageChannel 用法全解析
前端