UIWebView注入cookie

_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-NavHeight)];

    _webView.delegate = self;

    _webView.scalesPageToFit = YES;

    _webView.allowsInlineMediaPlayback = YES;

    _webView.mediaPlaybackRequiresUserAction = NO;

    [self.view addSubview:_webView];


//获取cookie

    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:self.financeUrl]];

    NSMutableDictionary *cookieDict = [NSMutableDictionary dictionary];

    for (NSHTTPCookie *cookie in cookies) {

        [cookieDict setValue:cookie.value forKey:cookie.name];

    }


    if (![[cookieDict objectForKey:@"PHPSESSID"] isKindOfClass:[NSString class]]) {

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"PHPSESSID"] isKindOfClass:[NSString class]] &&[[[NSUserDefaults standardUserDefaults] objectForKey:@"PHPSESSID"] length] >0) {

//Dictionary保存cookie

            [cookieDict setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"PHPSESSID"] forKey:@"PHPSESSID"];

            NSMutableDictionary *newCookieDic = [NSMutableDictionary dictionary];

            NSMutableArray *newCookieArr = [NSMutableArray arrayWithCapacity:0];

            for (id key  in cookieDict) {

                [newCookieDic setObject:key forKey:NSHTTPCookieName];

                [newCookieDic setObject:[cookieDict objectForKey:key] forKey:NSHTTPCookieValue];

                [newCookieDic setObject:[[NSURL URLWithString:self.financeUrl] host] forKey:NSHTTPCookieDomain];

                [newCookieDic setObject:@"/" forKey:NSHTTPCookiePath];

                [newCookieDic setObject:@"0" forKey:NSHTTPCookieVersion];

    //newCookie可能为空

                NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:newCookieDic];

                if (newCookie !=nil) {

                    [newCookieArr addObject:newCookie];

//注入cookie

                    [sharedHTTPCookieStorage setCookies:newCookieArr forURL:[NSURL URLWithString:self.financeUrl] mainDocumentURL:nil];

                }

            }

        }

    }

注:注入cookie需在加载URL之前有效。

    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.financeUrl]]];

你可能感兴趣的:(UIWebView注入cookie)