首页 > 解决方案 > 如何在 swift 中使用自定义 url 加载 webview

问题描述

我有一个函数给一个字符串并请求 webview 加载它但 webview 不加载这里是我的代码

class BrowserModel{

    func requestToURL(_ search:String)->WKWebView{
        if let url = URL(string: "https://google.com/search?q=\(search.encode)"){
            let webview = WKWebView()
            let request = URLRequest(url: url)
            webview.load(request)
            print("not nil")
            return webview
        }
        return WKWebView()
    }
}

我尝试使用此代码向我自己请求 Searchbar 委托,但 webview 未加载

 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

            webview = myWebview.requestToURL(self.searchbar.text!)
            print("search pressed")
    }

标签: iosswiftxcode

解决方案


正如我在评论中提到的,问题出在本地 Web 视图生命周期中,尝试使用 WKWebView 的扩展,这里是如何

    extension WKWebView {

    func loadURL(_ string: String) {
        guard let url = URL(string: "https://google.com/search?q=\(string)") else { return }
        load(URLRequest(url: url))
    }

}

这是搜索功能

private func addObserver() {
    searchBar.rx.text.orEmpty
        .distinctUntilChanged()
        .debounce(.seconds(1), scheduler: MainScheduler.instance)
        .subscribe(onNext: { query in
            self.webView.loadURL(query)
        }, onError: { error in
            print(error.localizedDescription)
        })
        .disposed(by: disposeBag)
}

在您的情况下,您可以使用

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
     webView.loadURL(searchbar.text ?? "")
}

推荐阅读