欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cookie

程序员文章站 2024-03-20 13:33:34
...

参考:
ios htttp网络请求cookie的读取与写入

NSHTTPCookieStorage(获取和删除cookie)

iOS中Cookie介绍


1、在请求(post、get、上传)中设置在本地中存储的cookie
manager.requestSerializer.HTTPShouldHandleCookies = YES;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[manager.requestSerializer setValue:[ud objectForKey:@"dictCookies"] forHTTPHeaderField: @"Cookie"];
2、网络回调response中拿到是否超时state状态
3、在登录接口response中来获取cookie存到本地
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSDictionary *dictCookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[cookieJar cookies]];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setObject:dictCookies[@"Cookie"] forKey:@"dictCookies"];
4、登录超时、登出时删除cookie
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies])
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"baseId"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"loginId"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"dictCookies"];
5.webview设置cookie
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlString]];
//设置Cookies
[request setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"dictCookies"] forHTTPHeaderField: @"Cookie"];
[_webview loadRequest:request];
6.webview获取登陆超时状态
NSString *responseString = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText"];
NSData *data= [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
7. 需要重新登录
if ([[jsonObject objectForKey:@"state"] isEqualToString:@"1103"]) {//后台规定1103,就是超时了,下面进行超时处理

[_webview addSubview:[self accImageView]];

[WebViewController relogin];

}

设置不能多台设备同时登录:可以每次登录,后台更新cookie。