我是论坛的新手,也是 iOS Dev 的新手。我在使用 UIWebView 时遇到问题,我不断失去对设置 phpsession cookie 的 HTML 表单的登录权限(过期设置为 8h,可在桌面上使用)。似乎 UIWebView 在大约一个小时左右而不是 8 小时后将 cookie 扔掉。我读过 NSHTTPCookieStorage 应该自动处理 cookie,即使在应用进入后台模式或退出后也是如此。
NSHTTPCookie 看起来像这样
NSHTTPCookie 版本:0 名称:“PHPSESSID” 值:“6f267fdc94c1ce5fcsdgg49b59a8f46b” 到期日期:2013-02-21 01:27:58 +0000 创建:2001-01-01 00:00:01 +0000 (1 ) sessionOnly:FALSE 域:"mydomain.com"路径:"/"isSecure:FALSE
我确实在退出/ sleep 时将它保存到 NSUserDefaults 中,并在进入前台/打开应用程序时再次加载它,就像这里推荐的那样:How to set my web view loaded with already login user -iPhone - 仍然,我总是丢失登录信息。
谁能给我指明方向?非常感谢!
我目前正在这样做(根据下面的帖子):
NSURL *lastURL = [[self.webView request] mainDocumentURL];
if (lastURL.absoluteString == NULL) {
lastURL = [NSURL URLWithString:@"http://mydomain.com/"];
}
NSArray *cookiesForDomain = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://mydomain.com"]];
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:lastURL];
for (NSHTTPCookie *cookie in cookiesForDomain) {
NSString *cookieString = [NSString stringWithFormat:@"%@=%@", [cookie name], [cookie value]];
[newRequest setValue:cookieString forHTTPHeaderField:@"Cookie"];
NSLog(@"inserted cookie into request: %@", cookie);
}
[self.webView loadRequest:newRequest];
最佳答案
我在我的应用程序中使用了很多请求,每次发送请求时,我都会从 NSHTTPCookieStorage
获取 url 的 cookie。我不使用 NSUserDefaults
或其他东西来存储 cookie。
当我发送新请求时,我会自行设置所需的 cookie
NSURL *myURL = ....
NSMutableRequest *mutableRequest = ....
NSArray *cookiesToSet = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:myURL];
for (NSHTTPCookie *cookie in cookiesToSet) {
[cookieStringToSet appendFormat:@"%@=%@;", cookie.name, cookie.value];
}
if (cookieStringToSet.length) {
[mutableRequest setValue:cookieStringToSet forHTTPHeaderField:@"Cookie"];
}
它有效
关于ios - 在 UIWebView 中不断丢失 php session cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14997879/