Recently developed new features, which have the need to load Web pages, and recently learned that the Wkwebview, said that the memory consumption is small, fast loading, and JS interactive good. Because the need to interact with the Web page, and the previous use of UIWebView to find the interaction with the Web page is not very good, so this decision to use Wkwebview.
As you experience the joy of using new controls and better controls, a new problem arises-loading web pages and not getting cookies in time. The background can not get cookies in time, when loading the Web page can not be loaded into the correct data. (You need to add more pages to load the correct data)
After consulting the relevant information, we found that we need to manually add cookies to the Web page when using Wkwebview. The previous use of the UIWebView will automatically cookies, all do not need us to worry about the background can not get cookies in time.
To add cookies manually when using Wkwebview:
Nsmutabledictionary *cookiedic = [Nsmutabledictionary dictionary];
nsmutablestring *cookievalue = [nsmutablestring stringwithformat:@ "];
Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage];
For (Nshttpcookie *cookie in [Cookiejar cookies]) {
[Cookiedic SetObject:cookie.value ForKey:cookie.name];
}
Cookie repeat, first put in the dictionary to go to the heavy, and then splicing
For (NSString *key in Cookiedic) {
NSString *appendstring = [NSString stringwithformat:@ "%@=%@;", key, [Cookiedic Valueforkey:key]];
[Cookievalue appendstring:appendstring];
}
Nsmutableurlrequest * request = [nsmutableurlrequest Requestwithurl:[nsurl URLWithString:self.url]];
[Request Addvalue:cookievalue forhttpheaderfield:@ "Cookie"];
NSLog (@ "Add cookie");
[Self.webview Loadrequest:request];