1
我想知道如何在Xcode中保存cookie。我想使用我從一個網頁獲得的cookie並使用它來訪問另一個網頁。我使用下面的代碼登錄到網站,並且我想保存從此連接獲得的cookie以在我建立另一個連接時使用它。保存cookies?
NSString *post = [NSString stringWithFormat: @"some data", _username, _password ];
// NSLog(@"%@",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSURL *url=[NSURL URLWithString:@"url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData;
NSHTTPURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
更新:感謝到iOS開發我能得到的cookie。下面的代碼是一個for循環來nslog所有的cookie名稱,域,值。幫助查看您當前存儲的所有Cookie。
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (int i = 0; i < [cookies count]; i++) {
NSHTTPCookie *cookie = [cookies objectAtIndex:i];
NSLog(@"Cookie Name: %@", [cookie name]);
NSLog(@"Cookie Domain: %@", [cookie domain]);
NSLog(@"Cookie Value: %@", [cookie value]);
}
好感謝訪問它,你爲什麼有這麼多的餅乾,我怎樣才能得到一個我想要的嗎? –
當您與服務器建立連接時,您的Cookie將被更新爲新的cookie。你將不得不遍歷cookie來獲得正確的cookie。 – Rajesh