iOS development Wkwebview Cookie Read and write, shared with UIWebView cookie

Source: Internet
Author: User
Tags cache and cookies

Nshttpcookiestorage and Nshttpcookie

Nshttpcookiestorage implements a singleton object that manages cookies (only one instance), each of which is an instance of the Nshttpcookie class, and as a rule, the cookie is shared between all applications and is kept synchronized between the different processes. The Session cookie (a cookie that issessiononly method returns YES) can only be used in a single process.

UIWebView cookies

In the same application, the cookies between different UIWebView are automatically synchronized. and can be accessed by other network classes such as Nsurlconnection,afnetworking.

They are all stored in the Nshttpcookiestorage container. When UIWebView loads a URL, the Http Response, the cookie is written, updated or deleted, and the result is updated to the Nshttpcookiestorage storage container when the load is completed.

Wkwebview Cookies

Nsurlcache and Nshttpcookiestroage cannot manipulate (Wkwebview) the cache and cookies of webcore processes.

Wkwebview instances will ignore any default network storage (Nsurlcache, Nshttpcookiestorage, nscredentialstorage) and some standard custom network request classes (NSURLPROTOCOL, etc.).

Wkwebview instances do not deposit cookies into the app standard cookie container (nshttpcookiestorage), because nsurlsession/ Nsurlconnection and other network requests to use Nshttpcookiestorage to access cookies, so the Wkwebview cookie is not accessible, the phenomenon is Wkwebview stored a cookie, Other network classes, such as nsurlsession/nsurlconnection, are not visible. ,

The same situation as a cookie is the Wkwebview cache, credentials, and so on. Wkwebview have their own private storage, so it's not as good to be compatible with standard cocoa network classes.

You also cannot customize the requests (add your own HTTP header, change the already existing header) to use the custom URL schemes, and so on, because Nsurlprotocol also does not support Wkwebview.

Http://stackoverflow.com/questions/24464397/how-can-i-retrieve-a-file-using-WKWebView

Wkwebview Cookie Write

Using the traditional UIWebView-era method of writing has been tested to be ineffective, and we look forward to Apple adding more features to the new SDK version, but the problem is that our app is not just for the new iOS version, so the old version also needs a different approach to solve the problem.

JS Injection 1

wkusercontentcontroller* Usercontentcontroller = wkusercontentcontroller.new;
Wkuserscript * Cookiescript = [[Wkuserscript alloc] Initwithsource: @ "document.cookie = ' teskcookiekey1= TeskCookieValue1 ';d ocument.cookie = ' teskcookiekey2=teskcookievalue2 '; " Injectiontime:wkuserscriptinjectiontimeatdocumentstart Formainframeonly:no];

[Usercontentcontroller Adduserscript:cookiescript];
wkwebviewconfiguration* webviewconfig = wkwebviewconfiguration.new;
Webviewconfig.usercontentcontroller = Usercontentcontroller;
Wkwebview * WebView = [[Wkwebview alloc] Initwithframe:cgrectmake (/*set your values*/) configuration:webviewconfig];

JS Injection 2

-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) Navigation {
[WebView evaluatejavascript:@ "document.cookie = ' teskcookiekey1=teskcookievalue1 ';" completionhandler:^ (id result, Nserror *error) {
//...
}];
}

Nsmutableurlrequest

Nsmutableurlrequest *request= [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:@ "http://dev.skyfox.org/ Cookie.php "];
[Request Sethttpshouldhandlecookies:yes];
[Request setvalue:[nsstring stringwithformat:@ "%@=%@", @ "Testwkcookie", @ "Testwkcookievalue"] forhttpheaderfield:@ " Cookie "];

Attention:

JS injected cookies, such as PHP code in the cookie container is not available, JavaScript document.cookie can be read, the browser can also be seen.

Nsmutableurlrequest injected PHP and other dynamic language directly can be obtained from the $_cookie object, but JS cannot read, the browser can not see

So a reasonable way to let js,php, the browser can read the same cookie method is to create webview when JavaScript injects a cookie, the first time to send a nsmutableurlrequest request to add a cookie, and guarantee the setting of two places the cookie is consistent.

Initialization
wkusercontentcontroller* Usercontentcontroller = wkusercontentcontroller.new;
Wkuserscript * Cookiescript = [[Wkuserscript alloc] Initwithsource: @ "document.cookie = ' teskcookiekey3= TeskCookieValue3 '; " Injectiontime:wkuserscriptinjectiontimeatdocumentstart Formainframeonly:no];

[Usercontentcontroller Adduserscript:cookiescript];
wkwebviewconfiguration* webviewconfig = wkwebviewconfiguration.new;
Webviewconfig.usercontentcontroller = Usercontentcontroller;
Wkwebview * WebView = [[Wkwebview alloc] Initwithframe:cgrectmake (/*set your values*/) configuration:webviewconfig];

Request
Nsmutableurlrequest *request= [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:@ "http://dev.skyfox.org/ Cookie.php "];
[Request Sethttpshouldhandlecookies:yes];
[Request setvalue:[nsstring stringwithformat:@ "%@=%@", @ "TeskCookieKey3", @ "TeskCookieValue3"] forhttpheaderfield:@ "Cookie");
[WebView Loadrequest:request];

Wkwebsitedatastore

Introduced in iOS 9 and Os X 10.11, Wkwebsitedatastore is a new API for managing data stored on a site site, such as cookies, which is a read-write property on the wkwebviewconfiguration of your Web page. You can delete data based on type or time, such as cookies and caches, and you can change the configuration with non-persistent data storage.

Wkwebview Cookie Read 1.http respone headerfields

Because the cookie has HTTP Respone headerfields, find the Wkwebview callback that can get respone, print.

-(void) WebView: (Wkwebview *) WebView decidepolicyfornavigationresponse: (Wknavigationresponse *) navigationresponse Decisionhandler: (void (^) (wknavigationresponsepolicy)) decisionhandler{
Nshttpurlresponse *response = (Nshttpurlresponse *) navigationresponse.response;
Nsarray *cookies =[nshttpcookie cookieswithresponseheaderfields:[response allheaderfields] forURL:response. URL];
Read the cookie method in Wkwebview 1
For (Nshttpcookie *cookie in cookies) {
[[Nshttpcookiestorage Sharedhttpcookiestorage] Setcookie:cookie];
NSLog (@ "cookie:%@ in Wkwebview", cookie);

}
Read the cookie method in Wkwebview 2 read the Set-cookie field
NSString *cookiestring = [[Response Allheaderfields] valueforkey:@ "Set-cookie"];
NSLog (@ "cookie:%@ in Wkwebview", cookiestring);

See if it's deposited in the nshttpcookiestorage.
Nshttpcookiestorage *cookiejar2 = [Nshttpcookiestorage sharedhttpcookiestorage];
For (Nshttpcookie *cookie in cookiejar2.cookies) {
NSLog (@ "cookie%@ in Nshttpcookiestorage", cookie);
}
Decisionhandler (Wknavigationresponsepolicyallow);
}

The result does read the cookie, but the cookie found in the printed Nshttpcookiestorage Singleton does not have any cookies.

2.WKWebsiteDataStore iOS9

Called after page load is complete
-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) navigation{
Wkwebsitedatastore *datastore = [Wkwebsitedatastore Defaultdatastore];
[DataStore Fetchdatarecordsoftypes:[wkwebsitedatastore Allwebsitedatatypes]
completionhandler:^ (Nsarray<wkwebsitedatarecord *> * __nonnull Records) {
For (Wkwebsitedatarecord *record in Records)
{
NSLog (@ "wkwebsitedatarecord:%@", [record description]);
}
}];
}

Demo Address

iOS development Wkwebview Cookie Read and write, shared with UIWebView cookie

Related Article

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.