iOS UIWebView 添加 cookie

272 阅读1分钟
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];
    
    // add cookies before load request
    NSString *cookieJS = [self addCookiesWithDomain:@"xxx.x.x.xxx"];
    // JS
    [self.webView stringByEvaluatingJavaScriptFromString:cookieJS];
    
    NSString *urlString = @"https://xxx.x.x.xxx/url.html";
    NSURL *url = [NSURL URLWithString:urlString];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (NSString *)addCookiesWithDomain:(NSString *)domain {
    
    NSDictionary *cookieDic = @{
                                @"userId":@"101",
                                @"userType":@"1",
                                @"key":@"xxxxxxxxxxx"
                                };
    NSMutableArray *cookiesArr = [[NSMutableArray alloc] init];
    NSMutableString *cookieString = [NSMutableString stringWithFormat:@""];
    
    for (NSString *key in cookieDic) {
        NSString *value = cookieDic[key];
        NSDictionary *dic = @{
                              NSHTTPCookieName   : key,
                              NSHTTPCookieValue  : value,
                              NSHTTPCookieDomain : domain,
                              NSHTTPCookiePath   : @"/",
                              NSHTTPCookieVersion: @"0",
                              NSHTTPCookieExpires: @"3600"
                              };
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dic];
        [cookiesArr addObject:cookie];
        
        NSString *appendString = [NSString stringWithFormat:@"document.cookie='%@=%@';", key, value];
        [cookieString appendString:appendString];
    }
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookiesArr forURL:[NSURL URLWithString:domain] mainDocumentURL:nil];
    
    NSString *utf8 = [cookieString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    cookieString   = [NSMutableString stringWithString:utf8];
    return cookieString;
}