2015-02-24 88 views
0

我正在構建一個iOS應用程序,在該應用程序中,我實現了Fabric並使用數字進行登錄。登錄成功時,會話保持打開狀態。如何清除目標C中的應用程序緩存?

我正要面對一個問題,我想清除應用程序緩存以重置會話,以便用戶可以使用新的電話號碼重新登錄。但它沒有發生。

的代碼我使用清除應用程序緩存:

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    [[NSURLCache sharedURLCache] removeAllCachedResponses]; 

} 

幫助表示讚賞!

+0

在哪裏登錄邏輯?您如何在應用程序中保存登錄信息? – 2015-02-24 11:51:10

+1

爲什麼要低級別和NSURLCache混亂,而不是使用你的圖書館自己的高級機制?你不能只是做一些像[[Digits sharedInstance] logOut]'? – Clafou 2015-02-24 13:15:11

+0

非常感謝! @ Clafou,對我來說絕對完美。 – Daljeet 2015-02-24 13:34:58

回答

2

而不是去低級別和惹NSURLCache,您可以使用圖書館的自己的高級別機制:

[[Digits sharedInstance] logOut] 
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]; 
      } 
     } 
    } 
} 
+0

感謝@亞歷山大的回覆......但它不工作,即使這不是我的NSUserDefaults。 – Daljeet 2015-02-24 13:21:47

+0

是的,似乎@Clafou確實在我沒有理解這個問題時。我的代碼片段將適用於位於NSURCache之上或使用NSURLCredentials的低級抽象。 – 2015-02-24 14:09:41

+0

是的,你是對的亞歷山大任何方式感謝您的建議。 – Daljeet 2015-02-24 14:10:54

相關問題