欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS cookie的使用

程序员文章站 2022-05-09 13:50:43
...

将接受到的 token 放在cookie里面

root是我的IP地址

   tokenStr = @"";
   root = @"";

    //保存 包含 accessToken的Cookies
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:@"accessToken"  forKey:NSHTTPCookieName]; //给cookie取名
    [cookieProperties setObject:tokenStr forKey:NSHTTPCookieValue];
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; //存放目录
    NSString * domain = [NSURL URLWithString:root].host;
    [cookieProperties setObject:domain forKey:NSHTTPCookieDomain]; //设置域名
    NSHTTPCookie * httpCookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:httpCookie]; //存入仓库

// 如果是token 每次登陆 或者动态监测过期时间 会改变等 保持cookie唯一 可以选择使用这个

//清除多余的token 
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSLog(@"Cookie:%@",cookies);
    for (NSHTTPCookie *tempCookie in cookies)
    {
        [cookieStorage deleteCookie:tempCookie];
    }
    ```