iOS WKWebView新增Cookie

黑暗森林的歌者發表於2018-02-26

網路請求新增Cookie都需要在request的時候新增

//獲取Cookie
- (NSString *)getCurrentCookie {
    NSMutableString *cookieStr = [[NSMutableString alloc] init];
    NSArray *array =  [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    if ([array count] > 0) {
        for (NSHTTPCookie *cookie in array) {
            [cookieStr appendFormat:@"%@=%@;",cookie.name,cookie.value];
        }
        //刪除最後一個分號 “;”
        [cookieStr deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
    }
    return cookieStr;
}
複製程式碼

給request增加請求頭

NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.myAttachUrl]];
NSString *cookie = [self getCurrentCookie];
[myRequest addValue:cookie forHTTPHeaderField:@"Cookie"];
複製程式碼

WKWebView載入請求

[self.myWKWebView loadRequest:self.myRequest];
複製程式碼

相關文章