如何在目标C中清除应用程序的缓存?

时间:2015-02-24 11:44:34

标签: ios objective-c caching nsurlcache

我正在构建一个iOS应用程序,其中我已经实现了Fabric并使用Digits进行登录。当登录成功时,会话保持打开状态。

我遇到问题我想清除应用缓存以重置会话,以便用户可以使用新的电话号码重新登录。但它没有发生。

我用来清除应用缓存的代码:

- (void)viewDidLoad {

    [super viewDidLoad];

    [[NSURLCache sharedURLCache] removeAllCachedResponses];

}

感谢帮助!

2 个答案:

答案 0 :(得分:4)

由于您的问题的某些关键部分缺失(例如您使用的身份验证方法),我只会在此处发布一个方便的代码段,可以解决您的问题。

但请注意:这将删除所有cookie和所有缓存的响应以及所有NSURLCredentials(只要它们不被保留)。

- (void)removeAllStoredCredentials
{
    // Delete any cached URLrequests!
    NSURLCache *sharedCache = [NSURLCache sharedURLCache];
    [sharedCache removeAllCachedResponses];

    // Also delete all stored cookies!
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [cookieStorage cookies];
    id cookie;
    for (cookie in cookies) {
        [cookieStorage deleteCookie:cookie];
    }

    NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
    if ([credentialsDict count] > 0) {
        // the credentialsDict has NSURLProtectionSpace objs as keys and dicts of userName => NSURLCredential
        NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
        id urlProtectionSpace;
        // iterate over all NSURLProtectionSpaces
        while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
            NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
            id userName;
            // iterate over all usernames for this protectionspace, which are the keys for the actual NSURLCredentials
            while (userName = [userNameEnumerator nextObject]) {
                NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userName];
                //NSLog(@"credentials to be removed: %@", cred);
                [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
            }
        }
    } 
}

答案 1 :(得分:2)

您可以使用图书馆自己的高级机制,而不是低级别并且与NSURLCache混乱,

[[Digits sharedInstance] logOut]