iosswiftuserdefaultsios-lifecycle

iOS mobile application first ever app launch detect


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?


Solution

  • 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)
    }