Send Request code:
NSString *testurl = @ "Http://10.22.122.7:8081/test2_action/view_index"; Nsurl *url = [nsurl Urlwithstring:testurl]; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy timeOutInterval:60]; nsstring *value = [nsstring stringWithFormat:@ "wap_0000e86bebfc4514987ae63acf9d19dd=123",]; [Request Setvalue:value Forhttpheaderfield:@ "Cookie"]; [_webview loadrequest:request];
Results: In-page jump, cookie invalidation
Problem cause Analysis:
Wkwebview carries a cookie on the first load, and then Wkwebview automatically clears the cookie when the page jumps in the Wkwebview, causing the user to log in two times.
Workaround:
When creating a WebView object, place the cookie in the Wkwebview to carry the cookie for all requests.
The following is the implementation code: (Here the cookie does not work when the first request, in the H5 page to jump again when it will work, unknown reason)
wkusercontentcontroller* Usercontentcontroller = [[Wkusercontentcontroller alloc] init]; Wkuserscript * Cookiescript = [[Wkuserscript alloc]initwithsource: [nsstring stringWithFormat:@ "document.cookie = ' wap_cookie_enable=1 ';d ocument.cookie = ' Wap_ 0000e86bebfc4514987ae63acf9d19dd=%@ '; ", user. WAP_0000E86BEBFC4514987AE63ACF9D19DD] Injectiontime:wkuserscriptinjectiontimeatdocumentstart fo Rmainframeonly:NO]; [Usercontentcontroller Adduserscript:cookiescript]; Wkwebviewconfiguration *configuration = [[Wkwebviewconfiguration alloc] Init];configuration.usercontentcontroller = Usercontentcontroller; [Configuration.usercontentcontroller Addscriptmessagehandler: Selfname:@ "Redirect"]; Self.webview = [[[Wkwebview alloc] initWithFrame:self.view.bounds configuration:configuration] autorelease];
Note the point:
1, the creation of the WebView when the cookie, the beginning of the request when the time to add a cookie,
2. Ensure that the cookie that starts sending the request is consistent with the cookie here.
Ios-wkwebview carry a cookie to send an HTTP request, the cookie expires