有关cookie是什么,大家可以自行百度,本文我获得cookie的目的是得到一个userID。
下面的是代码。
- (void)getUserIDFromCookie{ NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:urlStr]; NSEnumerator *enumerator = [cookies objectEnumerator]; NSHTTPCookie *cookie; while (cookie = [enumerator nextObject]) { NSLog(@"%@,%@", [cookie name], [cookie value]); }}
由此得到的cookie,大家可以根据cookie里面的内容进行遍历,来得到自己想要的值。
对于ios 来说 NSHTTPCookieStorage 会存储APP自身访问所有url的cookie,可以用domain为标志来获取自己所需要的cookie。需要注意的是,NSHTTPCookieStorage存储的cookie在过期后会自动删除,如用户手动调整时间超过期时间则系统也会自动删除,因此某些业务逻辑需要注意。
设置cookie:
- (void)setCookie{ NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];// 设置 cookie 的参数 [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];}
接下来说下清除所有cookie:
NSHTTPCookie *cookie;NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies]) { [sharedHTTPCookieStorage deleteCookie:cookie]; } // 缓存 清除 [[NSURLCache sharedURLCache] removeAllCachedResponses];
清除某个url下的cookie:
- (void)deleteCookie{ NSHTTPCookie *cookie; NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSArray *cookieAry = [sharedHTTPCookieStorage cookiesForURL: [NSURL URLWithString:urlStr]]; for (cookie in cookieAry){ [sharedHTTPCookieStorage deleteCookie:cookie]; }}
参考文章: