How to detect Apps first launch in iOS?

前端 未结 7 934
小蘑菇
小蘑菇 2020-12-01 06:11

I would like to display a welcome screen when a user opens my app for the first time. What method is there to check the first launch of an app in Swift?

7条回答
  •  执念已碎
    2020-12-01 06:41

    A slight semantic modification of Jonas Deichelmann's answer, clarifying a few things:

    • The function name "establishUserDefaultsHaveBeenVerifed" provides a suggestion that the userDefaults aren't just being checked, but may also be written to.
    • The key previously suggested, "isAppAlreadyLaunchedOnce", describes something the function itself has no control over; that key will only correctly describe the launch state if the function is called at the right time by other code, which again, the function itself can't control. Using the key "userDefaultsHaveBeenVerified" instead makes clear that the only thing the function verifies is that it itself has been run before.
    • The print statements make clear that this function is only verifying if it has been run since last installation, not whether or not it has ever been run on this device.

      func establishUserDefaultsHaveBeenVerifed()->Bool{
           let defaults = UserDefaults.standard
           if let _ = defaults.string(forKey: "userDefaultsHaveBeenVerified"){
               print("user defaults were already verified")
               return true
            }else{
               defaults.set(true, forKey: "userDefaultsHaveBeenVerified")
               print("verified user defaults for first time since app was installed")
               return false
            }
       }
      

提交回复
热议问题