iOS mobile application first ever app launch detect

154 Views Asked by At

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?

2

There are 2 best solutions below

1
Md. Ashikur Rahman On BEST ANSWER

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)
}
1
Cy-4AH On

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.