While there is no function or handler for checking when the app has been uninstalled from the phone, we can check if it is the apps first launch. More than likely when an app is first launched, that also means it has just been installed and nothing has been configured within the app. This process will be executed in didfinishLaunchingWithOptions
above the return true
line.
First, we have to set up the User Defaults:
let userDefaults = UserDefaults.standard
After this, we need to check if the app has launched before or has been run before:
if (!userDefaults.bool(forKey: "hasRunBefore")) {
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
}
We have now checked if it is the apps first launch or not. Now we can try to log out our user. Here is how the updated conditional should look:
if (!userDefaults.bool(forKey: "hasRunBefore")) {
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
}
We have now checked if the user is launching the app for the first time, and if so, log out a user if one was previously signed in. All the code put together should look like the following:
let userDefaults = UserDefaults.standard
if (!userDefaults.bool(forKey: "hasRunBefore")) {
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
}