【问题标题】:PHP cookie is not staying set in uiwebviewPHP cookie 未在 uiwebview 中保持设置
【发布时间】:2015-12-22 07:18:48
【问题描述】:

我有一个具有登录名的 UIWebView。登录是一个 PHP 脚本并且有一个 setcookie() 函数。 cookie 是在我登录(在 webview 中)但当我关闭应用程序(使用 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(仅限)代码来设置 PHP cookie,这样我就不必再次登录了?

【问题讨论】:

  • 你能把你的 UIWebView 的代码放上去吗?
  • 如何在我的项目中实现它?我是初学者,不知道怎么弄。

标签: php ios objective-c cookies uiwebview


【解决方案1】:

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

【讨论】:

  • 你的意思是 - cookiesToSet
  • 我没有收到任何错误。当我打开应用程序并登录时,cookies 就设置好了。但是当我关闭应用程序并重新打开它时,cookie 并没有保持设置。
  • 您的 cookie 不会在执行之间保留,您需要将其保存到磁盘..
  • 添加到代码时出现错误,如何实现?
猜你喜欢
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多