Http://www.cnblogs.com/lys-iOS-study/p/5856378.html
In a network request, there is a part of the need to add cookies, and then the way to add cookies to the Web is a small list, in fact, all the network requests to add cookies include the Web, and ultimately will be added to the request, as follows:
if (_webview = = nil) {
//1) Create WebView
_webview = [[Wkwebview alloc] Initwithframe:cgrectmake (0, 0, Kwidth, kheight -64)];
2 Set agent
_webview.delegate = self;
_webview.scalespagetofit = YES;
_webview.scrollview.bounces = NO;
}
3) Set URL address
nsurl *url = [Nsurl Urlwithstring:strurl];
Nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url];
Nsdictionary *cookie = [AppInfo shareappinfo].usermodel.cookies;
if (cookie!= nil) {
[request addvalue:[self Readcurrentcookiewith:cookie] forhttpheaderfield:@ "Cookie"];
else{
[Request addvalue:@ "" forhttpheaderfield:@ "Cookie"];
}
[_webview loadrequest:request];
[Self.view Addsubview:_webview];
1 |
<codeclass= "Hljs Objectivec" > </code> |
Where I got the cookie information I encapsulated it:
#pragma mark-Stitching Cookie
-(nsstring*) Readcurrentcookiewith: (nsdictionary*) dic{
if (dic = nil) {return
nil ;
} else{
Nshttpcookiestorage*cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage];
nsmutablestring *cookiestring = [[Nsmutablestring alloc] init];
for (Nshttpcookie*cookie in [Cookiejar cookies]) {
[cookiestring appendformat:@ "%@=%@;", Cookie.name,cookie.value ];
}
Delete the last ";"
[Cookiestring Deletecharactersinrange:nsmakerange (Cookiestring.length-1, 1)];
Return cookiestring
}
}
[Self setcookie];//set cookies
Before this, set cookies.
Set cookies
-(void) setcookie{
nsmutabledictionary *cookieproperties = [nsmutabledictionary dictionary];
[Cookieproperties setobject:@ "Cookie_user" forkey:nshttpcookiename];
[Cookieproperties Setobject:uid forkey:nshttpcookievalue];
[Cookieproperties setobject:@ "xxx.xxx.com" forkey:nshttpcookiedomain];
[Cookieproperties setobject:@ "/" forkey:nshttpcookiepath];
[Cookieproperties setobject:@ "0" forkey:nshttpcookieversion];
[cookieproperties setobject:[[nsdate Date] datebyaddingtimeinterval:2629743] forkey:nshttpcookieexpires];
Nshttpcookie *cookieuser = [Nshttpcookie cookieproperties];
[[Nshttpcookiestorage Sharedhttpcookiestorage] setcookie:cookieuser];
}
Nshttpcookiestorage The cookie that implements the management share stores a singleton object (shared instance). These cookies are shared between all applications and synchronized across processes to save
Clear cookies
-(void) deletecookie{
nshttpcookie *cookie;
Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage];
Nsarray *cookieary = [Cookiejar cookiesforurl: [Nsurl urlwithstring: _urlstr]];
For (cookies in cookieary) {
[Cookiejar Deletecookie:cookie];
}
}