我正在尝试按照this链接中建议的UIWebView
保存会话:
- (NSURLRequest*)addCookies:(NSArray *)cookies forRequest:(NSURLRequest *)request
{
NSMutableURLRequest *mutableRequest = [request mutableCopy];
if ([cookies count] > 0)
{
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies)
{
if (!cookieHeader)
{
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
}
else
{
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader)
{
[mutableRequest setValue:cookieHeader forHTTPHeaderField:@"Cookie"];
}
return [mutableRequest copy];
}
return nil;
}
在viewDidLoad
:
NSURLRequest *webRequest = [NSURLRequest requestWithURL:homeURL];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSMutableURLRequest *requestMut = [NSMutableURLRequest requestWithURL:webRequest.URL];
[requestMut setHTTPShouldHandleCookies:YES];
webRequest = [self addCookies:cookies forRequest:requestMut];
[_tgWebView loadRequest:webRequest];
但是应用程序再次出现在登录屏幕上,即会话未保存。 This是一个类似的问题,我刚才发现了这个问题 更新:我试图将Cookie的到期日期设置为大约十年,但问题仍未解决:
+ (void)loadCookies
{
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"SAVED_COOKIES"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies)
{
NSMutableDictionary *newProperties = [[NSMutableDictionary alloc]initWithDictionary:cookie.properties];
NSDate *date = [newProperties objectForKey:NSHTTPCookieExpires];
if(date == nil)
[newProperties setObject:[[NSDate date] dateByAddingTimeInterval:100*12*30*60*60] forKey:NSHTTPCookieExpires];
else
[newProperties setObject:[[NSDate date] dateByAddingTimeInterval:100*12*30*60*60] forKey:NSHTTPCookieExpires];
NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:newProperties];
[cookieStorage setCookie: newCookie];
NSLog(@"%@",newCookie);
}
}
答案 0 :(得分:11)
这只是一种可能的实施方式: 首先存储cookie
- (void)saveCookies {
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey: @"cookies"];
[defaults synchronize];
}
恢复Cookie:
- (void)loadCookies {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey: @"cookies"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies) {
[cookieStorage setCookie: cookie];
}
}