-1

In my app, I want to check how long ago did the user last open the app and if it was 14 days or more, the user would receive a prompt saying they should be more active but I'm not too sure how to check how long ago was the app last used.

Jia Chen
  • 43
  • 7

3 Answers3

1

Store the current date in UserDefaults whenever the app becomes inactive (using the applicationWillResignActive app delegate).

Load the stored date (if any) from UserDefaults whenever the app becomes active (using the applicationDidBecomeActive app delegate). If there is a date (there won't be the first time the app is used), calculate the number of days between the retrieved date and the current date.

See Swift days between two NSDates for methods to calculate the difference between two dates. In short, you use the Calendar dateComponents(_, from:, to:) method.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

In your AppDelegate:

func applicationWillResignActive(_ application: UIApplication) {
    UserDefaults.standard.set(Date(), forKey: "LastOpened")
}

func applicationDidBecomeActive(_ application: UIApplication) {
    guard let lastOpened = UserDefaults.standard.object(forKey: "LastOpened") as? Date else {
        return
    }
    let elapsed = Calendar.current.dateComponents([.day], from: lastOpened, to: Date())
    if elapsed >= 14 {
        // show alert
    }
}
keeshux
  • 592
  • 3
  • 10
0

save current Date(UserDefaults) on applicationWillTerminate(_:) & applicationDidEnterBackground(_:) methods.

check it on application(_:didFinishLaunchingWithOptions:)

Lal Krishna
  • 15,485
  • 6
  • 64
  • 84