Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing session between AFNetworking and UIWebView

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?

like image 876
RyanB Avatar asked Jan 25 '26 08:01

RyanB


2 Answers

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.

like image 128
RyanB Avatar answered Jan 28 '26 00:01

RyanB


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

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

like image 29
Xen Avatar answered Jan 28 '26 01:01

Xen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!