Talking about the Wkwebview in iOS add cookies

Source: Internet
Author: User

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];

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.