How to set a Cookie with a NSURLRequest?

后端 未结 4 2052
一向
一向 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: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.

提交回复
热议问题