SwiftUI: WKWebView not loading

后端 未结 1 1440
囚心锁ツ
囚心锁ツ 2021-01-23 09:23

I have a WKWebView as UIViewRepresentable in my SwiftUI application and it works initially. The webpage is loaded and I can navigate to other pages. If I force the web view to l

相关标签:
1条回答
  • 2021-01-23 10:03

    You try to apply 'reference'-base approach to value based SwiftUI views. It is not allowed, so does not work. In your usage code webView in button action and in below are different independent values (because WebView is struct).

    So here is possible approach. Tested with Xcode 11.4 / iOS 13.4

    demo

    struct TestWebView: View {
        @State private var shouldRefresh = false
        var body: some View {
            VStack{
                Button(action: {
                    self.shouldRefresh = true
                }){
                    Text("Reload")
                }
                WebView(url: nil, reload: $shouldRefresh)
            }
        }
    }
    
    
    struct WebView: UIViewRepresentable{
    
        var url: URL?     // optional, if absent, one of below search servers used
        @Binding var reload: Bool
    
        private let urls = [URL(string: "https://google.com/")!, URL(string: "https://bing.com")!]
        private let webview = WKWebView()
    
        fileprivate func loadRequest(in webView: WKWebView) {
            if let url = url {
                webView.load(URLRequest(url: url))
            } else {
                let index = Int(Date().timeIntervalSince1970) % 2
                webView.load(URLRequest(url: urls[index]))
            }
        }
    
        func makeUIView(context: UIViewRepresentableContext<WebView>) -> WKWebView {
            loadRequest(in: webview)
            return webview
        }
    
        func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
            if reload {
                loadRequest(in: uiView)
                DispatchQueue.main.async {
                    self.reload = false     // must be async
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题