iOS UIWebView completes the automatic login instance through cookie

  • 2021-12-21 05:17:28
  • OfStack

1. Related introduction

cookie obtained by iOS in UIWebView: NSHTTPCookieStorage * nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];

Then specifically obtain cookie: NSArray * cookiesURL = [nCookies cookiesForURL: [NSURL URLWithString: @ "Your URL"]] of a certain domain;

Save cookies by [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie: userCookie], but although cookies can be saved, it will still be lost after your application exits (in fact, it is the problem that cookies expires). The good way is to save cookies in NSUserDefaults.

2. Implement

1. In the proxy method of UIWebView, get cookies and put cookies into NSUserDefaults to save:-(void) webViewDidFinishLoad: (UIWebView*) webView to write

- (void)webViewDidFinishLoad:(UIWebView*)webView{
  NSArray *nCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookies];
  for (NSHTTPCookie *cookie in nCookies){
    if ([cookie isKindOfClass:[NSHTTPCookie class]]){
      if ([ isEqualToString:@"PHPSESSID"]) {
        NSNumber *sessionOnly =[NSNumber numberWithBool:cookie.sessionOnly];
        NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
        NSArray *cookies = [NSArray, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
        [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookies"];

2. Get cookies: After running, get the saved cookies before UIWebView loads url, and set cookies.

NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"];
  if (cookies.count >0) {
    NSMutableDictionary *cookieProperties = [NSMutableDictionarydictionary];
    [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
    [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
    [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
    NSHTTPCookie *cookieuser = [NSHTTPCookiecookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];

Note: To be in [self. webView loadRequest: req]; Get cookies before setting!

Related articles: