iOS Cookie的配置及使用
2017-07-11 本文已影响180人
上冬十二
cookie12x.png本文介绍iOS中cookie的使用包含AFNetWorking 3.0中的使用,常用于登录状态信息保存
- 从 NSHTTPCookieStorage 获取想要Cookie,此种获取方式是获取的cookies中的
//获取cookie
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,[NSString stringWithFormat:@"/index.php?route=mapi/%@",urlstring]]]];
for (NSHTTPCookie *tempCookie in cookies)
{
//打印cookies
NSLog(@"getCookie:%@",tempCookie);
}
NSDictionary *Request = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSUserDefaults *userCookies = [NSUserDefaults standardUserDefaults];
[userCookies setObject:[Request objectForKey:@"Cookie"] forKey:@"cookie"];
[userCookies synchronize];
cookie22x.png
- 清除Cookie
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *_tmpArray = [NSArray arrayWithArray:[cookieStorage cookies]];
for (id obj in _tmpArray) {
[cookieStorage deleteCookie:obj];
}
使用 AFNetworking 时,对Cookies管理的示例
- AFNetworking 3.0 默认是保存cookies的。
- 模拟登录,保存cookie以及设置cookie:
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *httpManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"hostURL"] sessionConfiguration:sessionConfiguration];
AFHTTPRequestSerializer *requestSerialization = [AFHTTPRequestSerializer serializer];
requestSerialization.timeoutInterval = 15;
// 设置自动管理Cookies
requestSerialization.HTTPShouldHandleCookies = YES;
// 如果已有Cookie, 则把你的cookie符上
NSString *cookie = [[NSUserDefaults standardUserDefaults] objectForKey:@"Set-Cookie"];
if (cookie != nil) {
[requestSerialization setValue:cookie forHTTPHeaderField:@"Set-Cookie"];
}
// 安全策略
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
securityPolicy.validatesDomainName = NO;
[httpManager POST:@"logInURL"
parameters:nil
progress:NULL
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
//获取 Cookie
NSHTTPURLResponse* response = (NSHTTPURLResponse* )task.response;
NSDictionary *allHeaderFieldsDic = response.allHeaderFields;
NSString *setCookie = allHeaderFieldsDic[@"Set-Cookie"];
if (setCookie != nil) {
NSString *cookie = [[setCookie componentsSeparatedByString:@";"] objectAtIndex:0];
// 这里对cookie进行存储
[[NSUserDefaults standardUserDefaults] setObject:cookie forKey:@"cookie"];
}
}else{
// 登录失败
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *errorMessage = error.userInfo[@"NSLocalizedDescription"];
}];
附上我的博客链接:oragekk'Blog 欢迎留言-不过评论系统换成了disqus需要搭梯子哦