2013-02-21 50 views
3

我是新来的论坛,也是iOS Dev的新手。我在使用UIWebView时遇到了麻烦,在这种情况下,我一直失去登录权限,无法登录设置phpsession cookie(过期时间设置为8小时,可在桌面上运行)的HTML表单。看起来UIWebView在大约一个小时左右之后抛出cookie,而不是8小时。我已经阅读NSHTTPCookieStorage应该自动处理cookie,即使应用程序进入后台模式或退出。继续在UIWebView中丢失php会话cookie

的NSHTTPCookie看起来像这样

NSHTTPCookie版本:0名: “PHPSESSID” 值: “6f267fdc94c1ce5fcsdgg49b59a8f46b” expiresDate:2013年2月21日1时27分58秒+0000创建:2001-01-01 00 :00:01 +0000(1)sessionOnly:FALSE域: “mydomain.com” 路径: “/” 的isSecure:FALSE

而且我保存退出/进入睡眠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]; 

回答

5

我在我的应用程序的许多要求,每次使用时,我发送请求我得到的饼干从NSHTTPCookieStorage的URL。我不使用NSUserDefaults或其他东西来存储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"]; 
} 

和它的作品

+0

会立即尝试!谢谢! – alberto2000 2013-02-21 09:46:58

+0

那么,即使使用您的解决方案,我仍然失去登录...还有什么想法? – alberto2000 2013-02-21 10:42:44

+0

确保你在cookiesToSet中有cookie。 (你可以把断点放在for循环中)。 – Mert 2013-02-21 11:18:04