gpt4 book ai didi

ios - 如何让 UIWebView session 永不过期

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:11 24 4
gpt4 key购买 nike

我正在尝试按照 this 中的建议在 UIWebView 上保存 session 链接:

- (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];

但应用程序再次出现在登录屏幕上,即 session 未保存。 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);
}
}

最佳答案

这只是一个可能的实现:首先存储cookie

- (void)saveCookies {
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey: @"cookies"];
[defaults synchronize];
}

恢复cookies:

- (void)loadCookies {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey: @"cookies"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies) {
[cookieStorage setCookie: cookie];
}
}

关于ios - 如何让 UIWebView session 永不过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com