我们需要在每个网页URL中添加查询参数(isfromMobile = true),这是识别请求来自后端移动应用程序所必需的。第一页上的加载绝对正常,但是,如果我单击webview内的链接,则url更改完全是后端系统的新URL。按照逻辑,移动应用程序也应在该URL上嵌入查询参数。我尝试使用以下webview的委托方法修复该问题。
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
request.url = request.url?.getMobileUrl() // this adds the query parameter in url eg : testurl?isFromMobile=true
return true
}
但是,我发现请求参数在此委托中不是可变的,每次创建新请求肯定会增加Web URL的加载时间,或者我不希望这样做。相同的任何更好的建议。
答案 0 :(得分:1)
首先,请使用WKWebView
。然后,您可以使用WKNavigationDelegate decidePolicyForNavigationAction
方法来检查加载网址,如果没有所需的查询参数,请调整该网址并重新加载:
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView?
var loadUrl = URL(string: "https://stackoverflow.com/tags?isFromMobile=true")!
override func viewDidLoad() {
super.viewDidLoad()
// .. all your other code here
// Load first request with initial url
loadWebPage(url: loadUrl)
}
func loadWebPage(url: URL) {
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
components?.query = nil
// If already has a query then append a param
// otherwise create a new one
if let query = url.query {
// If isFromMobile param already exists jsut reassign the existing query
if query.contains("isFromMobile=true") {
components?.query = query
} else {
components?.query = query + "&isFromMobile=true"
}
} else {
components?.query = "isFromMobile=true"
}
let customRequest = URLRequest(url: components!.url!)
loadUrl = components!.url!
webView!.load(customRequest)
}
// MARK: - WKNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
// If url changes, cancel current request which has no custom parameters
// and load a new request with that url with custom parameters
if url != loadUrl {
decisionHandler(.cancel)
loadWebPage(url: url)
} else {
decisionHandler(.allow)
}
}
}
答案 1 :(得分:0)