Reputation: 55
I have webView in which I load some url. I need to set custom header for that URLRequest. For the first request it works as expected, header is received on server side and content is displayed accordingly. However if I open another link from displayed page, headers are lost and request is sent without header.
My lucky guess is that, header is added only for the first time and I have to add it every time when request to load url is sent. However I couldn't find method where can I do so.
Currently I'm setting header in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
let url = URL(string: "https://mywebsite.com");
var requestobj = URLRequest(url: url!);
requestobj.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
myWebView.loadRequest(requestobj);
}
Am I missing something or should I add header in different place for every request?
Upvotes: 1
Views: 1195
Reputation: 55
Ok, thanks to iphonic, to pointing at shouldStartLoadWith. I could use that to understand is request new or old one and solve my problem by doing so:
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool{
if(navigationType == UIWebViewNavigationType.linkClicked)
{
var req = request;
req.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
self.myWebView.loadRequest(req);
return false;
}
else {
return true;
}
}
So here I check, if navigation type is clickedLink, then I don't load current request, instead I copy it, reapply custom header and load it into myWebView. If navigationType isn't linkClicked, I proceed request without changes.
Upvotes: 1