Is it possible to share AFNetworking
session with UIWebView? I used AFNetworking
to login to remote server, but the UIWebView have no idea about the session being created by AFNetworking
?
Actually, AFNetworking
and UIWebView
share the same cookies storage. So we don't need any special technique to let UIWebView
"share" a session initialized by AFNetworking
, or any native session-based request which uses NSHTTPCookieStorage
to store cookie. In my situation, the UIWebView
did not find shared session to be useful, just because the session initialized by AFNetworking
has lacked of a cookie which was sent only when browsing the site with a browser.
And here is what I did to solve the problem:
// Open a request to remote server with a User-Agent string set to the request header.
// We'll have browser-specific cookies in NSHTTPCookieStorage
NSString *userAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
[manager GET:kRemoteServerUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Done");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Failure");
}];
Above code will ensure that we have all browser-specific cookies in NSHTTPCookieStorage, hence let the UIWebView
share any session initialized by native login routine.