我正在使用WKWebView加载一些网页。我需要在WKWebView中传递一些标题来改变语言。我已成功通过,但在服务器端,它显示其他语言。请告诉我传球机制是对还是错。
- (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);
}
答案 0 :(得分:0)
您的代码中有两个错误:
1)您定义标题字段太晚(在webview已经开始使用请求加载页面之后)
2)您在实际请求的可变副本上设置标题(因此不在使用的标题上)。一旦方法完成,该副本就会被释放。
在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.
您无需对webView:decidePolicyForNavigationAction:decisionHandler:
委托方法中的标题字段执行任何操作。