Reputation: 930
I am a newbie here for ios, swift and Xcode.
I have a component of WKWebView
. And I want to add some headers while onClick
for redirecting to another page in the WKWebView
. How can I override or add the headers? If in Android
version, I can do like:
webView.setWebViewClient(new WebViewClient() {
:
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest url) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
view.loadUrl(url.getUrl().toString(), extraHeader);
}
return true;
}
:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
view.loadUrl(url, extraHeader);
}
return true;
}
:
}
I have already done like this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: BASE_URL)
let request = NSMutableURLRequest(url: url!)
request.addValue(MOBILE, forHTTPHeaderField: X_CLIENT_TYPE)
self.webView.load(request as URLRequest)
}
But, the code above is only for first loading. If I click a link in WKWebView
, the headers are gone.
So, it is my pleasure for anyone can help me...
env:
- XCode v. 9.3
Upvotes: 2
Views: 4028
Reputation: 930
I have already found a solution:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("decidePolicyFor")
let request = navigationAction.request
print("request: ", request)
if ( (request.url?.absoluteString.hasPrefix(BASE_URL))! && request is NSMutableURLRequest) {
print("NSMutableURLRequest")
let mutableRequest = request as! NSMutableURLRequest;
let clientType = mutableRequest.value(forHTTPHeaderField: X_CLIENT_TYPE) as String?
print("clientType: ", clientType)
if (clientType != nil && clientType == MOBILE) {
print("client type is MOBILE")
} else {
print("add client type MOBILE")
mutableRequest.addValue(MOBILE, forHTTPHeaderField: X_CLIENT_TYPE)
webView.load(mutableRequest as URLRequest)
}
decisionHandler(WKNavigationActionPolicy.allow)
} else {
print("NOT NSMutableURLRequest")
decisionHandler(WKNavigationActionPolicy.allow)
}
}
Upvotes: 3
Reputation: 7193
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
// If you have post parameter pass here
let postString = "key=\(Value!)&Key=\(Value!)"
request.httpBody = postString.data(using: .utf8)
// Set your Header here
request.setValue("MOBILE", forHTTPHeaderField:"X_CLIENT_TYPE")
if request != nil
{
webView.loadRequest(request)
webView.delegate = self
}
You Can Do for Second Click
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType:
UIWebViewNavigationType) -> Bool
{
var Myrequest = URLRequest.init(url: request.url!)
Myrequest.setValue("MOBILE", forHTTPHeaderField:"X_CLIENT_TYPE")
webView.loadRequest(Myrequest)
true
}
Upvotes: 1