Reputation: 1257
I am working on WKWebView for loading some web pages. I need to pass some header inside WKWebView for change of language. I have passed successfully, however on server side, its showing other language. Please let me know whether the mechanism of passing is right or wrong.
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@""];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"%@",navigationAction.request.allHTTPHeaderFields);
NSMutableURLRequest *request = [navigationAction.request mutableCopy];
[request setValue:@"sv" forHTTPHeaderField:@"Accept-Language"];
decisionHandler(WKNavigationActionPolicyAllow);
}
Upvotes: 2
Views: 12007
Reputation: 4424
There are two mistakes in your code:
1) You define the header fields too late (after the webview has already started to use the request to load the page)
2) You set the header on a mutable copy of the actual request (so not on the one that's used). This copy is then just dealloced once the method finishes.
Try this here in your viewDidLoad
:
// ... start as you did
NSURL *nsurl=[NSURL URLWithString:@""]; // I assume you're using a correct URL in your actual code?
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:nsurl];
[request setValue:@"sv" forHTTPHeaderField:@"Accept-Language"];
[self.view addSubview:webView];
[webView loadRequest:nsrequest]; // I just prefer to add to the view hierarchy before I do anything with it, personal preference.
You do not need to do anything regarding the header fields in your webView:decidePolicyForNavigationAction:decisionHandler:
delegate method.
Upvotes: 1