0

I was trying to initiate an integer value in UserDefaults. But I want to do this operation once. At the first launch.

func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UserDefaults.standard.set(-1, forKey: Constant.shared.empId)
       return true
    }

I tried this the above way. But didFinishLaunchingWithOptions is calling every time I launch the app. is there any function that is called once during the app's whole life cycle?

3 Answers3

1

You need call:

UserDefaults.standard.register(
  defaults: {
    Constant.shared.empId: -1
  }
)

It will be called every time on app launch, but will not override value set with set method.

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22
  • It should be mentioned that this code would replace the OP's existing `UserDefaults` code in `didFinishLaunchingWithOptions`. – HangarRash Mar 27 '23 at 02:28
1

First, you can check whether userDefault contains any value or not. If it doesn't have any value, then you can set it. Following code may help you.

if UserDefaults.standard.object(forKey: Constant.shared.empId) != nil {
            
    print("UserDefaults has a value")
}
else {
    print("UserDefaults doesn't have a value")
    UserDefaults.standard.set(-1, forKey: Constant.shared.empId)
}
  • While this may work, it is far from the best solution. The other answer about registering a default is a much cleaner approach. – HangarRash Mar 27 '23 at 02:27
-1
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Check if this is the first launch
    if UserDefaults.standard.bool(forKey: "isFirstLaunch") {
        // Perform any necessary setup tasks or show a welcome screen
        // ...
        
        // Set isFirstLaunch to false
        UserDefaults.standard.set(false, forKey: "isFirstLaunch")
    }
    
    return true
}
Saranjith
  • 11,242
  • 5
  • 69
  • 122