在APP開發(fā)中,cookie也開始變的越來越重要了勋功。為了更好的切換,注銷和登錄賬戶辅甥,就必須熟悉cookie的用法酝润。
花了點時間把代碼整理了一下,注釋也都標(biāo)上了
1璃弄,獲取cookie
獲取cookie只能在請求中獲取cookie要销,否則時獲取不到的,url就不給出了夏块,大家用自己的url測試一下就行疏咐。
獲取到cookie后把cookie進(jìn)行歸檔保存到userDefaults里
#pragma mark 獲取并保存cookie到userDefaults
- (void)getAndSaveCookie
{
NSLog(@"=============獲取cookie==============");
NSString *urlString = @"";
//請求一個網(wǎng)址,即可分配到cookie
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer new];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//獲取cookie
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *tempCookie in cookies) {
//打印獲得的cookie
NSLog(@"getCookie: %@", tempCookie);
}
/*
* 把cookie進(jìn)行歸檔并轉(zhuǎn)換為NSData類型
* 注意:cookie不能直接轉(zhuǎn)換為NSData類型脐供,否則會引起崩潰浑塞。
* 所以先進(jìn)行歸檔處理,再轉(zhuǎn)換為Data
*/
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
//存儲歸檔后的cookie
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject: cookiesData forKey: @"cookie"];
NSLog(@"\n");
[self deleteCookie];
[self setCoookie];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
nil;
}];
}
2政己,刪除cookie
把獲取到的cookie刪除掉酌壕,該步驟可以用在注銷或者切換賬號里。
當(dāng)前歇由,我這里刪除cookie是為了檢測后面的通過本地存儲的數(shù)據(jù)進(jìn)行設(shè)置cookie是否成功
#pragma mark 刪除cookie
- (void)deleteCookie
{
NSLog(@"============刪除cookie===============");
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
//刪除cookie
for (NSHTTPCookie *tempCookie in cookies) {
[cookieStorage deleteCookie:tempCookie];
}
//把cookie打印出來卵牍,檢測是否已經(jīng)刪除
NSArray *cookiesAfterDelete = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *tempCookie in cookiesAfterDelete) {
NSLog(@"cookieAfterDelete: %@", tempCookie);
}
NSLog(@"\n");
}
3,通過本地存儲的數(shù)據(jù)設(shè)置cookie
把本地的cookie取出并反歸檔沦泌,設(shè)置到cookie中糊昙,并且檢測cookie是否設(shè)置成功
#pragma mark 再取出保存的cookie重新設(shè)置cookie
- (void)setCoookie
{
NSLog(@"============再取出保存的cookie重新設(shè)置cookie===============");
//取出保存的cookie
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//對取出的cookie進(jìn)行反歸檔處理
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"cookie"]];
if (cookies) {
NSLog(@"有cookie");
//設(shè)置cookie
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (id cookie in cookies) {
[cookieStorage setCookie:(NSHTTPCookie *)cookie];
}
}else{
NSLog(@"無cookie");
}
//打印cookie,檢測是否成功設(shè)置了cookie
NSArray *cookiesA = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *cookie in cookiesA) {
NSLog(@"setCookie: %@", cookie);
}
NSLog(@"\n");
}
看一下運行截圖
屏幕快照 2015-05-19 下午5.29.45
最后谢谦,奉上demo
Coo