Сначала используйте WKWebView
. Затем вы можете использовать метод WKNavigationDelegate decidePolicyForNavigationAction
, чтобы проверить URL-адрес загрузки, и если у него нет требуемых параметров запроса, отрегулируйте URL-адрес и перезагрузите его:
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)
}
}
}