Sharing session between AFNetworking and UIWebView

隐身守侯 提交于 2019-12-08 02:58:09

问题


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?


回答1:


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

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




回答2:


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.



来源:https://stackoverflow.com/questions/37540108/sharing-session-between-afnetworking-and-uiwebview

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