3

在我的 iPhone 应用程序中,要注销我的客户端,我需要删除给定 URL 的 cookie。

编写代码很容易,来自 AFNetworking 的 @matt 提供了一个简单的代码示例。

- (void)cleanCookies
{
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:kBaseURL]];
    for (NSHTTPCookie *cookie in cookies)
    {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

这很容易。现在在我的单元测试中,我想证明我的代码正在删除与这个 baseURL 相关的 cookie。

问题,如何将 NSHTTPCookie 添加到 NSHTTPCookieStorage 以便我可以使用

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:kBaseURL]];

我正在尝试像这样添加cookie:

NSMutableDictionary *newCookieDict = [NSMutableDictionary dictionaryWithCapacity:6];
            [newCookieDict setObject:@"cookiie" forKey:NSHTTPCookieName];
            [newCookieDict setObject:@"/api" forKey:NSHTTPCookiePath];
            [newCookieDict setObject:@"2020-10-26 00:00:00 -0700" forKey:NSHTTPCookieExpires];
            [newCookieDict setObject:kSkyStoreBaseURL forKey:NSHTTPCookieOriginURL];
            [newCookieDict setObject:kSkyStoreBaseURL forKey:NSHTTPCookieDomain];
            [newCookieDict setObject:@"value" forKey:NSHTTPCookieValue];

            // Create a new cookie
            NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:newCookieDict];

            // Add the new cookie
            NSHTTPCookieStorage *cookiesStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            [cookiesStore setCookies:@[newCookie] forURL:[NSURL URLWithString:kSkyStoreBaseURL] mainDocumentURL:nil];

cookie 被正确添加,但是当我为指定的 baseURL 调用它时,我得到一个 nil 值!

NSArray *cookies = [cookiesStore cookiesForURL:[NSURL URLWithString:kSkyStoreBaseURL]];

cookies = nil :\

以前有人经历过吗?

4

0 回答 0