PHP cookie不会保留在uiwebview中

时间:2015-09-24 15:41:23

标签: php ios objective-c cookies uiwebview

我有一个有登录的UIWebView。登录是一个PHP脚本,并具有setcookie()函数。我在登录时(在webview中)设置了cookie,但是当我关闭应用程序(使用webview)并重新打开它时。 PHP cookie未设置,我必须重新登录。

这是PHP代码

setcookie($_SESSION['id'], $_SESSION['user_name'], time() + (86400 * 3), "/"); 
setcookie($_SESSION['pro_pic'], $_SESSION['status'], time() + (86400 * 3), "/"); 
setcookie($_SESSION['pro_pic'], $_SESSION['email'], time() + (86400 * 3), "/"); 

UIWebivew的代码

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];

    NSString *url=@"http://server.bithumor.co/bitpicks/index1.php";
    NSURL *nsurl=[NSURL URLWithString:url];
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];

    [webview loadRequest:nsrequest];

    webview.scrollView.bounces = NO;

    [self.view addSubview:webview];
    [self.view bringSubviewToFront:webview];
}

在正常的Safari浏览器中,Cookie保持设置并完美运行。但它在UIWebView中不起作用。

我使用什么objective-c(only)代码来保持PHP cookie设置,以便我不必再次登录?

1 个答案:

答案 0 :(得分:0)

如此所指Keep losing php session cookie in UIWebView我更新了您的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];

    NSString *url=@"http://server.bithumor.co/bitpicks/index1.php";
    NSURL *nsurl=[NSURL URLWithString:url];
    NSMutableURLRequest *nsrequest=[NSMutableURLRequest requestWithURL:nsurl];

    NSString *cookiesSaved = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"];

    NSMutableString *cookieStringToSet = (cookiesSaved ? [NSMutableString stringWithString:cookiesSaved] : [NSMutableString new]);

    NSArray *cookiesToSet = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:nsurl];
    for (NSHTTPCookie *cookie in cookiesToSet) {

        if ([cookieStringToSet rangeOfString:cookie.name].location == NSNotFound)
        {
            [cookieStringToSet appendFormat:@"%@=%@;", cookie.name, cookie.value];
        }
    }

    [[NSUserDefaults standardUserDefaults] setObject:cookieStringToSet forKey:@"cookies"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [webview loadRequest:nsrequest];

    webview.scrollView.bounces = NO;

    [self.view addSubview:webview];
    [self.view bringSubviewToFront:webview];
}