// // ViewController.m // cookie // // Created by 谭启宏 on 16/3/4. // Copyright © 2016年 tqh. All rights reserved. // #import "ViewController.h" static NSString*kLocalCookieName =@"MyProjectCookie"; static NSString*kLocalUserData =@"MyProjectLocalUser"; static NSString*kServerSessionCookie =@"JSESSIONID"; @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //保存cookie + (void)saveLoginSession { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSArray *allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies]; NSMutableDictionary *cookieDictionary; for (NSHTTPCookie *cookie in allCookies) { if ([cookie.name isEqualToString:kServerSessionCookie]) { cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:kLocalCookieName]]; [cookieDictionary setValue:cookie.properties forKey:@"cookieDict"]; [defaults setValue:cookieDictionary forKey:kLocalCookieName]; [self updateSession]; [defaults synchronize]; break; }else if([cookie.name isEqualToString:@"jsessionId"]){ } } } //更新cookie + (void)updateSession { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSDictionary *cookieDictionary = [defaults dictionaryForKey:kLocalCookieName]; NSLog(@"%@",cookieDictionary); NSDictionary *cookieProperties = [cookieDictionary valueForKey:@"cookieDict"]; if (cookieProperties != nil) { NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; } } //删除cookie + (void)removeLoginSession{ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults removeObjectForKey:kLocalCookieName]; [defaults synchronize]; } @end