2016-11-22 88 views
5

從手機中卸載應用程序後,我的應用程序不會註銷當前用戶。我不希望用戶卸載應用程序,當他們重新安裝它們時,他們已經登錄。將應用程序卸載後將用戶註銷 - Firebase

我認爲這與它的鑰匙串訪問有關嗎?不確定。我想,也許我需要在應用程序被刪除後纔對用戶進行身份驗證,但是沒有辦法檢查這種情況。最接近的就是運行applicationWillTerminate函數,但是如果我把我的FIRAuth.auth()?.signOut()放在那裏,它會在每次應用程序被殺時簽署我的用戶。我不想那樣。

我該如何去做這項工作?

回答

12

雖然沒有功能或處理程序來檢查應用程序何時從手機上卸載,但我們可以檢查它是否是應用程序第一次啓動。當應用程序首次啓動時,這意味着它剛安裝完畢,應用程序中沒有任何配置。該過程將在return true行之上的didfinishLaunchingWithOptions中執行。

首先,我們要設置用戶默認值:

let userDefaults = UserDefaults.standard 

在此之後,我們需要檢查,如果應用程序之前已經推出或之前已運行:

if userDefaults.bool(forKey: "hasRunBefore") == false { 
    print("The app is launching for the first time. Setting UserDefaults...") 

    // Update the flag indicator 
    userDefaults.set(true, forkey: "hasRunBefore") 
    userDefaults.synchronize() // This forces the app to update userDefaults 

    // Run code here for the first launch 

} else { 
    print("The app has been launched before. Loading UserDefaults...") 
    // Run code here for every other launch but the first 
} 

我們有現在檢查它是否是應用程序第一次啓動。現在我們可以嘗試註銷我們的用戶。下面是如何更新的條件應該是:

if userDefaults.bool(forKey: "hasRunBefore") == false { 
    print("The app is launching for the first time. Setting UserDefaults...") 

    do { 
     try FIRAuth.auth()?.signOut() 
    } catch { 

    } 

    // Update the flag indicator 
    userDefaults.set(true, forkey: "hasRunBefore") 
    userDefaults.synchronize() // This forces the app to update userDefaults 

    // Run code here for the first launch 

} else { 
    print("The app has been launched before. Loading UserDefaults...") 
    // Run code here for every other launch but the first 
} 

現在我們已經檢查,如果用戶首次啓動時間的應用程序,如果是這樣,註銷用戶如果是在此前簽署的所有代碼放在一起應該看起來像下面這樣:

let userDefaults = UserDefaults.standard 

if userDefaults.bool(forKey: "hasRunBefore") == false { 
    print("The app is launching for the first time. Setting UserDefaults...") 

    do { 
     try FIRAuth.auth()?.signOut() 
    } catch { 

    } 

    // Update the flag indicator 
    userDefaults.set(true, forkey: "hasRunBefore") 
    userDefaults.synchronize() // This forces the app to update userDefaults 

    // Run code here for the first launch 

} else { 
    print("The app has been launched before. Loading UserDefaults...") 
    // Run code here for every other launch but the first 
} 
相關問題