PHP cookie is not staying set in uiwebview

2019-09-02 17:35发布

问题:

I have a UIWebView which has a login. The login is a PHP script and has a setcookie() function. The cookies are set when I login (in the webview) but when I close out the app (with the webview) and reopen it. The PHP cookies get unset and I must login again.

Here's the PHP code

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), "/"); 

Code for 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];
}

On the normal safari web browser, the cookies stay set and work perfectly. But it doesn't work in the UIWebView.

What objective-c (only) code do i use to keep the PHP cookies set so I won't have to sign in again?

回答1:

as pointed here Keep losing php session cookie in UIWebView I updated your code:

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