ios WKWebView Cookie settings

1. What is a Cookie

HTTP Cookie (also called browser or Web Cookie Cookie) is sent to the user's browser and the server locally saved a small piece of data, it will be carried on and sent to the server the next time the browser sends a request to the same server . Typically, it is used to tell two requests from the same server whether the browser, such as keeping the user's login status.

When the server receives the HTTP request, the server may add a setCookie response Set-Cookie header is used to send a cookie to the client by the server in response to the head inside. ") Option. After the browser receives the response is usually held at Cookie, after the server every time a request through Cookie is a request header, which contains the previous Set-Cookie header put and stored in the client from the server through the HTTP cookies . ") Cookie request header to send a message to the server. In addition, Cookie expiration time, domain, path, valid for the site can be specified as needed.

//设置Cookie
- (void)setCookie{
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:@"courseToken" forKey:NSHTTPCookieName]; // CookieName 也就是 字典Key
    [cookieProperties setObject:"123" forKey:NSHTTPCookieValue]; //Value也就是字典Key值
    [cookieProperties setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain]; //域  可以不用写
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
    [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
    [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires]; //有效期
    NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
    
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
  // 需要持久化的话 可以用 NSUserDefaults
}

// Clear Cookie

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];  
    if (url) {  
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];  
        for (int i = 0; i < [cookies count]; i++) {  
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];  
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];  
       }

// clear the specified cookie

NSArray * cookArray = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"URL"]];
 for (NSHTTPCookie*cookie in cookArray) { 
 if ([cookie.name isEqualToString:@"cookieName"]) { 
 [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie]; 
    } 
 } 

Reproduced in: https: //www.jianshu.com/p/a6d6b84c5b33

Guess you like

Origin blog.csdn.net/weixin_34336292/article/details/91072071