NSHTTPCookieStorage ios cookie

cookie機(jī)制采用的是在客戶端保持 HTTP 狀態(tài)信息的方案

Cookie是在瀏覽器訪問WEB服務(wù)器的某個(gè)資源時(shí)索绪,由WEB服務(wù)器在HTTP響應(yīng)消息頭中附帶傳送給瀏覽器的一個(gè)小文本文件恩闻。

一旦WEB瀏覽器保存了某個(gè)Cookie怪得,那么它在以后每次訪問該WEB服務(wù)器時(shí)尊勿,都會(huì)在HTTP請求頭中將這個(gè)Cookie回傳給WEB服務(wù)器。

底層的實(shí)現(xiàn)原理: WEB服務(wù)器通過在HTTP響應(yīng)消息中增加Set-Cookie響應(yīng)頭字段將Cookie信息發(fā)送給瀏覽器彤路,瀏覽器則通過在HTTP請求消息中增加Cookie請求頭字段將Cookie回傳給WEB服務(wù)器浅浮。

一個(gè)Cookie只能標(biāo)識(shí)一種信息沫浆,它至少含有一個(gè)標(biāo)識(shí)該信息的名稱(NAME)和設(shè)置值(VALUE)。

一個(gè)WEB站點(diǎn)可以給一個(gè)WEB瀏覽器發(fā)送多個(gè)Cookie滚秩,一個(gè)WEB瀏覽器也可以存儲(chǔ)多個(gè)WEB站點(diǎn)提供的Cookie专执。

瀏覽器一般只允許存放300個(gè)Cookie,每個(gè)站點(diǎn)最多存放20個(gè)Cookie郁油,每個(gè)Cookie的大小限制為4KB本股。

一、NSHTTPCookieStorage ?【轉(zhuǎn)自 http://rainbird.blog.51cto.com/211214/805173】

一 直以為iOS的http請求這塊很簡單應(yīng)該不支持記錄桐腌,保存痊末,或者使用cookie,可是想當(dāng)然歸想當(dāng)然哩掺,真用的時(shí)候凿叠,真研究了一下發(fā)現(xiàn)還真強(qiáng)大。經(jīng)過一 番的研究簡單說一下我的理解:當(dāng)你訪問一個(gè)網(wǎng)站時(shí)嚼吞,不管你愿意或者不愿意盒件,NSURLRequest都會(huì)幫你主動(dòng)記錄下來你訪問的站點(diǎn)設(shè)置的 cookie,而且很負(fù)責(zé)任的舱禽,當(dāng)你下次再訪問這個(gè)站點(diǎn)時(shí)炒刁,NSURLRequest會(huì)拿著上次保存下來了的cookie繼續(xù)去請求。這規(guī)律同樣適用于 ASIHTTPRequest誊稚。所以當(dāng)你做一些基于認(rèn)證的網(wǎng)絡(luò)請求時(shí)翔始,cookie不失為一個(gè)完美的解決方案。

那么怎么查看cookie呢里伯?很簡單:

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {

NSLog(@"%@", cookie);

}

這樣就列出了所有已保存的cookie,如果當(dāng)前為空怎么辦呢城瞎?隨便請求一個(gè)url嘍。

NSURLRequest *request = [NSURLRequest requestWithURL:

[NSURL URLWithString:@"http://blog.cnrainbird.com"]

cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData? ? timeoutInterval:3];

[NSURLConnection sendSynchronousRequest:request

returningResponse:nil

error:nil];

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {

NSLog(@"%@", cookie);

}

是不是得到了類似:

1

的東東疾瓮?這就是cookie啦

怎么清空cookie呢脖镀?

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];

for (id obj in _tmpArray) {

[cookieJar deleteCookie:obj];

}

這樣cookie就消失的一干二凈了。

會(huì)查看cookie了狼电,也會(huì)清空cookie了蜒灰,怎么設(shè)置指定的cookie呢?

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:@"username" forKey:NSHTTPCookieName];

[cookieProperties setObject:@"rainbird" forKey:NSHTTPCookieValue];

[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieDomain];

[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieOriginURL];

[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

這樣就可以了肩碟。輸入一下强窖,是不是得到了下面這樣的結(jié)果:

1

二、

1.NSHttpCookiesStorage是一個(gè)單例削祈,管理所有的Cookie翅溺,每個(gè)Cookie都是一個(gè)NSHTTPCookie的實(shí)例,所有應(yīng)用的cookies都被保存在這個(gè)NSHTTPCookieStorage的單例中,并且跨進(jìn)程同步未巫。 ?但為了安全窿撬,每個(gè)應(yīng)用都有自己的沙盒启昧,A應(yīng)用的cookie是不能被B應(yīng)用訪問的叙凡。

iOS Note: Cookies are not shared among applications in iOS.

2. cookie的接收模式有3種

NSHTTPCookieAcceptPolicyAlways,NSHTTPCookieAcceptPolicyNever,NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain

如果改變cookie的接收模式,會(huì)影響所有當(dāng)前正在使用cookie storage正在運(yùn)行的應(yīng)用密末。

Note:Changes made to the cookie accept policy affect all currently running applications using the cookie storage.

3.Session cookies (where the cookie object’sisSessionOnlymethod returnsYES) are local to a single process and are not shared.

4.NSHTTPCookieStorage的問題握爷,即當(dāng)更改或者刪除一個(gè)cookie時(shí),NSHTTPCookieStorage不是立即接收NSHTTPCookieManagerCookiesChangedNotification严里,然后進(jìn)行更改,而是有5s的延遲,

參考:http://stackoverflow.com/questions/5837702/nshttpcookiestorage-state-not-saved-on-app-exit-any-definitive-knowledge-docume

http://www.cocoabuilder.com/archive/cocoa/195413-nshttpcookiestorage-notification-troubles.html

一般解決方法是把cookie手動(dòng)的保存逾条,隔一段時(shí)間刷新厂庇,程序啟動(dòng)時(shí)再從NSDefaultUser中讀出

NSHTTPCookieStorage state not saved on app exit. Any definitive knowledge/documentation out there?

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市迷帜,隨后出現(xiàn)的幾起案子物舒,更是在濱河造成了極大的恐慌,老刑警劉巖戏锹,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件冠胯,死亡現(xiàn)場離奇詭異,居然都是意外死亡锦针,警方通過查閱死者的電腦和手機(jī)荠察,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來奈搜,“玉大人悉盆,你說我怎么就攤上這事〔雎穑” “怎么了舀瓢?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長耗美。 經(jīng)常有香客問我京髓,道長,這世上最難降的妖魔是什么商架? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任堰怨,我火速辦了婚禮,結(jié)果婚禮上蛇摸,老公的妹妹穿的比我還像新娘备图。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布揽涮。 她就那樣靜靜地躺著抠藕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蒋困。 梳的紋絲不亂的頭發(fā)上盾似,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天,我揣著相機(jī)與錄音雪标,去河邊找鬼零院。 笑死,一個(gè)胖子當(dāng)著我的面吹牛村刨,可吹牛的內(nèi)容都是我干的告抄。 我是一名探鬼主播,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼嵌牺,長吁一口氣:“原來是場噩夢啊……” “哼打洼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起逆粹,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤募疮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后枯饿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酝锅,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年奢方,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了搔扁。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,100評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蟋字,死狀恐怖稿蹲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鹊奖,我是刑警寧澤苛聘,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站忠聚,受9級特大地震影響设哗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜两蟀,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一网梢、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧赂毯,春花似錦战虏、人聲如沸拣宰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽巡社。三九已至,卻和暖如春手趣,著一層夾襖步出監(jiān)牢的瞬間晌该,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工回懦, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留气笙,地道東北人次企。 一個(gè)月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓怯晕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親缸棵。 傳聞我的和親對象是個(gè)殘疾皇子舟茶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評論 2 345

推薦閱讀更多精彩內(nèi)容