iOS设置cookie到web遇到的坑

作者: Iam光星人 | 来源:发表于2017-08-29 16:44 被阅读152次

    获取本地的cookie,[SystemConfigure shareSystemConfigure].get_kHttpURL]留意用自己本地的域名,获取本地的登录的cookie信息

    - (NSString *)accessToken {  
        NSString *token = @"";
        NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray<NSHTTPCookie *> *cookies = [cookieStorage cookiesForURL:[NSURL URLWithString:[SystemConfigure shareSystemConfigure].get_kHttpURL]];
        for (NSHTTPCookie *cookie in cookies) {
            if ([cookie.name isEqualToString:@"accessToken"]) {
                token = [NSString stringWithFormat:@"%@",cookie.value];
                [[TMCache sharedCache] setObject:token forKey:kLoginTokenKey];
                break;
            }
        }
        return token;
    }
    

    设置cookie到web,注意self.startPage为你h5的链接地址,[PCUserLevelService share].accessToken为你之前保存的token

    //解决cookie保存问题 h5添加cookie中accessToken
        NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray<NSHTTPCookie *> *cookies = [cookieStorage cookiesForURL:[NSURL URLWithString:self.startPage]];
        [cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableDictionary *properties = [[cookie properties] mutableCopy];
            [properties setValue: [PCUserLevelService share].accessToken forKey:NSHTTPCookieValue];
            [properties setValue:@"accessToken" forKey:NSHTTPCookieName];
            //将cookie过期时间设置为一年后
            NSDate *expiresDate = [NSDate dateWithTimeIntervalSinceNow:3600*24*30*12];
            properties[NSHTTPCookieExpires] = expiresDate;
            //下面一行是关键,删除Cookies的discard字段,应用退出,会话结束的时候继续保留Cookies
            [properties removeObjectForKey:NSHTTPCookieDiscard];
            //重新设置改动后的Cookies
            [cookieStorage setCookie:[NSHTTPCookie cookieWithProperties:properties]];
        }];
    

    相关文章

      网友评论

        本文标题:iOS设置cookie到web遇到的坑

        本文链接:https://www.haomeiwen.com/subject/igaodxtx.html