Sharing session between AFNetworking and UIWebView

2019-06-02 16:55发布

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-06-02 17:33

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

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-06-02 17:35

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.

查看更多
登录 后发表回答