ios WKWebView Cookie设置

1 、什么是Cookie

HTTP Cookie(也叫Web Cookie或浏览器Cookie)是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器下次向同一服务器再发起请求时被携带并发送到服务器上。通常,它用于告知服务端两个请求是否来自同一浏览器,如保持用户的登录状态。

当服务器收到HTTP请求时,服务器可以在响应头里面添加一个setCookie响应首部 Set-Cookie 被用来由服务器端向客户端发送 cookie。")选项。浏览器收到响应后通常会保存下Cookie,之后对该服务器每一次请求中都通过 Cookie是一个请求首部,其中含有先前由服务器通过 Set-Cookie 首部投放并存储到客户端的 HTTP cookies。")请求头部将Cookie信息发送给服务器。另外,Cookie的过期时间、域、路径、有效期、适用站点都可以根据需要来指定。

//设置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
}

// 清除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];  
       }

//清除指定的cookie

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

你可能感兴趣的:(ios WKWebView Cookie设置)