Sharing session between AFNetworking and UIWebView

孤人 提交于 2019-12-06 04:25:46

Try using the UIWebView+AFNetworking category's to call loadRequest.

http://cocoadocs.org/docsets/AFNetworking/3.1.0/Categories/UIWebView+AFNetworking.html

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!