- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:[self createConfiguration]];
self.wkWebView.navigationDelegate = self;
[self.view addSubview:self.wkWebView];
[self loadWebView];
}
- (void)loadWebView {
NSURL *url = [NSURL URLWithString:@"url address"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:[self appendCookie] forHTTPHeaderField:@"Cookie"];
[self.wkWebView loadRequest:request];
}
- (WKWebViewConfiguration *)createConfiguration {
NSString *cookieString = [self appendCookie];
WKUserContentController *userContentController = [WKUserContentController new];
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = userContentController;
return config;
}
- (NSString *)appendCookie {
NSDictionary *cookieDic = @{
@"userName" :@"name",
@"userId" :@"101",
@"projectId":@"5"
};
NSMutableString *cookieString = [NSMutableString stringWithFormat:@""];
for (NSString *key in cookieDic) {
NSString *kv = [NSString stringWithFormat:@"document.cookie='%@=%@';", key, [cookieDic valueForKey:key]];
[cookieString appendString:kv];
}
return cookieString;
}