5

As it is known, AFHTTPSessionManager in AFNetworking 2.0+ supports cookies.

But is it possible for AFHTTPRequestOperationManager in AFNetworking 2.0+ to support cookies?

WildCat
  • 1,961
  • 6
  • 24
  • 35

1 Answers1

10

Yes. AFNetworking uses the foundation URL Loading system, which handles cookies out of the box.

You can configure NSMutableURLRequest's setHTTPShouldHandleCookies and use NSHTTPCookieStorage to store them.

In Objective-C:

NSArray *cookieStorage = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
NSDictionary *cookieHeaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieStorage];
NSMutableURLRequest *request = [myRequestSerializer requestWith…];
for (NSString *key in cookieHeaders) {
    [request addValue:cookieHeaders[key] forHTTPHeaderField:key];
}

In Swift:

var request = NSMutableURLRequest() // you can use an AFNetworking Request Serializer to create this

if let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(url) {
    for (headerField, cookie) in NSHTTPCookie.requestHeaderFieldsWithCookies(cookieStorage) {
        request.addValue(cookie, forHTTPHeaderField: headerField)
    }
}
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • Could you point me toward a method to *clear* cookies? E.G., start a fresh session with the same manager? Thanks. – Reid Apr 07 '14 at 17:51