PHP cookie is not staying set in uiwebview

故事扮演 提交于 2019-12-12 03:23:50

问题


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


来源:https://stackoverflow.com/questions/32765553/php-cookie-is-not-staying-set-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!