How to set a Cookie with a NSURLRequest?

后端 未结 4 2008
一向
一向 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

    Try this

    [theRequest setValue:@"myCookie" forHTTPHeaderField:@"Cookie"];
    

    Edit:

    OP wants to know how to create a cookie. So here is some code

    NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"domain.com", NSHTTPCookieDomain,
                            @"\\", NSHTTPCookiePath,  
                            @"myCookie", NSHTTPCookieName,
                            @"1234", NSHTTPCookieValue,
                            nil];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    NSArray* cookieArray = [NSArray arrayWithObject:cookie];
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
    [request setAllHTTPHeaderFields:headers];
    
    0 讨论(0)
  • 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:

    <?php
        echo "<li>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 '<li><a href="">Blank reload</a>';
        echo '<li><a href="#" onclick="location.reload(true);">Javascript reload</a>';
    
        exit;
    ?>
    

    It worked for me after much trial and error. Good luck. :)

    0 讨论(0)
  • 2020-12-30 05:37

    There is source code to extract cookie string from NSHTTPURLResponse:

    static NSString *CookieFromResponse(NSHTTPURLResponse *response) {
        NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:response.allHeaderFields forURL:response.URL];
    
        NSMutableString *cookieStr = [NSMutableString string];
        for (NSHTTPCookie *cookie in cookies) {
            if (cookieStr.length) {
                [cookieStr appendString:@"; "];
            }
            [cookieStr appendFormat:@"%@=%@", cookie.name, cookie.value];
        }
        return cookieStr.length ? cookieStr : nil;
    }
    

    And to set cookie string to NSMutableURLRequest:

    NSString *cookieStr = CookieFromResponse(response);
    [request addValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    0 讨论(0)
  • 2020-12-30 05:39

    not sure it's still relevant, but in case someone find that useful, here's how you get the cookies after making a request. You should implement the selector connectionDidFinishLoading: in the object that was specified as a delegate to NSURLConnection (self in your case):

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
    

    in this connectionDidFinishLoading: selector you can access the cookies like that:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSHTTPCookieStorage * storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray * cookies = [storage cookiesForURL:connection.currentRequest.URL];
        for (NSHTTPCookie * cookie in cookies)
        {
            NSLog(@"%@=%@", cookie.name, cookie.value);
            // Here you can store the value you are interested in for example
        }
    }
    

    then later, this stored value can be used in requests like this:

    [request setValue:[NSString stringWithFormat:@"%@=%@", cookieName, cookieValue] forHTTPHeaderField:@"Cookie"];
    

    or more advanced setAllHTTPHeaderFields:, but remember to use the correct value in NSHTTPCookiePath field, see details here

    also NSHTTPCookieStorage has selector -setCookies:forURL:mainDocumentURL: that can also be used to set cookies.

    0 讨论(0)
提交回复
热议问题