How to set a Cookie with a NSURLRequest?

后端 未结 4 2055
一向
一向 2020-12-30 04:53

I\'m trying to create an login in my iPhone App.

NSURL *urlNew = [NSURL URLWithString:urlstring];
NSMutableURLRequest *theRequest = [NSMutableURLRequest req         


        
4条回答
  •  长情又很酷
    2020-12-30 05:37

    I had the same problem with a WKWebView showing the cookie on a PHP page on initial load but the cookie was cleared when page was reloaded/refreshed. Here's what I did to make it work.

    My WKWebView with the cookie setting:

    WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init]; // empty for now
    _awesomeWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfig];
    _awesomeWebView.UIDelegate = self;
    [self.view addSubview:_awesomeWebView];
    
    NSString *url = @"https://phpwebsitewithcookiehandling.com";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    // set all the cookies from my NSHTTPCookieStorage in the WKWebView too
    [request setHTTPShouldHandleCookies:YES];
    [request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];
    
    // set the cookie on the initial load
    NSString *cookie = @"status=awesome";
    [request setValue:cookie forHTTPHeaderField:@"Cookie"];
    NSLog(@"cookie set in WKwebView header: %@", cookie);
    
    [_awesomeWebView loadRequest:request];
    

    On my phpwebsitewithcookiehandling.com I used the following to verify it worked:

    status is: " . $_COOKIE['status'];
    
        // Here comes the magic which set the servers SET-COOKIE header (apparently) so it works on consecutive page loads
        setcookie('status', $_COOKIE['status'], time() + (86400 * 30), '/');
    
        echo '
  • Blank reload'; echo '
  • Javascript reload'; exit; ?>
  • It worked for me after much trial and error. Good luck. :)

提交回复
热议问题