Created
March 5, 2019 10:49
-
-
Save liaogang/5d50377c87a7e6b92e9b8a1b402c833b to your computer and use it in GitHub Desktop.
iOS separate cookie handler for multi users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
How to set cookieAcceptPolicy for ephemeral NSURLSession https://stackoverflow.com/questions/27290234/how-to-set-cookieacceptpolicy-for-ephemeral-nsurlsession | |
Multiple NSHTTPCookieStorage in the same app https://stackoverflow.com/questions/27132606/multiple-nshttpcookiestorage-in-the-same-app | |
NSHTTPCookieStorage for same URL but different users https://stackoverflow.com/questions/37597250/nshttpcookiestorage-for-same-url-but-different-users | |
*/ | |
@interface NSHTTPCookieStorage (applePrivateHeader) | |
-(id)_initWithIdentifier:(id)arg1 private:(BOOL)arg2; | |
@end | |
@interface User() | |
@property (nonatomic, strong) NSHTTPCookieStorage *myHTTPCookieStorage; | |
@end | |
@implementation User | |
-(instancetype)init | |
{ | |
self = [super init]; | |
if (self) { | |
//the [NSHTTPCookieStorage init] will generate a instance with no inner `NSHTTPCookieStorageInternal`, so. | |
_myHTTPCookieStorage = [[NSHTTPCookieStorage alloc] _initWithIdentifier: @"user_id_xxx" private:0]; | |
_myHTTPCookieStorage.cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways; | |
} | |
return self; | |
} | |
-(void)httpTask{ | |
NSURLSessionConfiguration *c =[NSURLSessionConfiguration ephemeralSessionConfiguration]; | |
c.HTTPCookieStorage = _myHTTPCookieStorage; | |
[[[NSURLSession sessionWithConfiguration: c] dataTaskWithRequest:request completionHandler:nil] resume]; | |
} | |
// load from file | |
-(void)(id)initWithCoder:(NSCoder *)aDecoder{ | |
NSArray<NSHTTPCookie*> *cookies = [aDecoder decodeObjectForKey:@"cookies"]; | |
for (NSHTTPCookie *cookie in cookies) { | |
[_myHTTPCookieStorage setCookie: cookie]; | |
} | |
} | |
//save to file | |
- (void)encodeWithCoder:(NSCoder *)aCoder | |
[aCoder encodeObject:_myHTTPCookieStorage.cookies forKey: @"cookies"]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment