ios - 如何在 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")
}
解决方案
正如我在评论中提到的,问题出在本地 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 ?? "")
}
推荐阅读
- android - 单击“在 Play 商店应用中打开”时出现“无效的动态链接”firebase 错误,尽管未在应用中使用任何动态链接
- javascript - 如何在 React js 中使用 forEach
- python - 有没有办法上传/压缩整个 anaconda 环境并使用 anaconda 重新创建它?
- python - 如何在 Kivy 中创建一个可由两个滑块调用的函数?论点应该如何?
- sql - 使用 MERGE INTO 和 sql/spark 用另一个表更新一个表
- javascript - 如何修复 Windows 10 上的代理服务器错误?
- python - 在 tkinter 中的所述按钮上方添加一个带有按钮的“条目”小部件
- html - 如何使左右侧边栏粘性滚动(高度不均匀)并仅在左右底部匹配时左右滚动?
- vue.js - vue 将共享计算函数编译到单独的包中
- c# - 实体框架成组查询与可为空的外键