ios - 保存 cookies ?

标签 ios cookies nsurlconnection html

我想知道如何在 Xcode 中保存 cookie。我想使用从一个网页获取的 cookie 并使用它访问另一个网页。我使用下面的代码登录该网站,我想保存从该连接获得的 cookie,以便在我建立另一个连接时使用它。

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 Dev,我能够获得 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 将在 NSHttpCookieStorage 中可用。

您可以通过以下方式访问它

NSArray *cookies = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]

关于ios - 保存 cookies ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026849/

相关文章:

objective-c - 使用 segue 在 Storyboard中的 View Controller 之间传递数据

objective-c - 关闭 MFMailComposeViewController : error: address doesn't contain a section that points to a section in a object file 时出现奇怪的错误

asp.net - 每个域最多 20 个 cookie - 为什么?

python - 在 Python 中使用 SimpleCookie 管理 token 生命周期

ios - 当我调用异步发布请求时如何发送正文中的值

objective-c - Xcode中类之间的简单变量传递

iphone - iOS 上是否可以使用动态链接框架?

Android:处理来自 HTTP Get-Request 的 Cookie

macos - NSURLConnection - 是否可以等待/阻止请求?

ios - UIWebview didReceiveAuthenticationChallenge