Starman
Starman

Reputation: 126

How to load webview with custom url in swift

I have a function give a string and request to webview to load it but webview not load here is my code

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()
    }
}

i try this code to request im self the Searchbar delegate but webview not load

 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

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

Upvotes: 0

Views: 1551

Answers (1)

Alexandr Kolesnik
Alexandr Kolesnik

Reputation: 2204

As I mentioned in comments, the problem is in local web view lifecycle, try to use extension of WKWebView, here is example of how to

    extension WKWebView {

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

}

And this is func for search

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)
}

in your case you can use

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

Upvotes: 1

Related Questions