Although there is no function or handler to check when the application was removed from the phone, we can check if the application is the first launch. Most likely, when the application starts for the first time, it also means that it has just been installed and nothing is configured in it. This process will be executed in didfinishLaunchingWithOptions above the line return true .
First, we must set the user defaults:
let userDefaults = UserDefaults.standard
After that, we need to check whether the application was launched before or was launched earlier:
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 }
Now we checked whether the application launches for the first time or not. Now we can try to log out of our user. Here's what the updated condition should look like:
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 }
Now we have checked whether the user launches the application for the first time, and if so, log out if the user has previously logged in. All compiled code should look like this:
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 }
source share