项目中遇到的问题
第一种:URL中出现特殊字符 '=' 等,需要编码
let url = URL(string: safeString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
第二种:iPhone中打开所有网页都正常,但ipad中打开某些网页正常,某些网页白屏,如
https://www.baidu.com
就白屏let config = WKWebViewConfiguration() config.defaultWebpagePreferences.preferredContentMode = .mobile let wk = WKWebView(frame: UIScreen.main.bounds, configuration: config)
整体代码:
struct CoscoWebView: UIViewRepresentable {
typealias UIViewType = WKWebView
let urlString: String?
func makeUIView(context: Context) -> WKWebView {
let config = WKWebViewConfiguration()
// 不做此配置设置, 大多数网页是可以正常打开的
// 但对于百度官网,会出现手机可以打开而ipad白屏(不断的在代理方法didStart 和 didFinish之间循环)
config.defaultWebpagePreferences.preferredContentMode = .mobile
let wk = WKWebView(frame: UIScreen.main.bounds, configuration: config)
// 设置代理
wk.navigationDelegate = context.coordinator
return wk
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if let safeString = urlString {
// 路径中出现某些特殊字符(如 = 等...),会返回nil,此处需要编码
if let url = URL(string: safeString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "") {
let request = URLRequest(url: url)
uiView.load(request)
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}
extension CoscoWebView {
class Coordinator: NSObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
}
}