Reputation: 73
I need a simple method of counting the seconds between the last time i closed an app and i opened it....is there any simple way to do so?
Nothing else in the code needs changing, only number of seconds between "lastAppClosingTime' and "app Launched is needed. I am thinking about using the 'timeserving' but I', unsure if it'll be efficient
I have a countdown in my app, requiring the user to press a button 10 minutes before the end, however i have no idea how to make the app calculate whenever the user failed the LAST check or not
Upvotes: 2
Views: 205
Reputation: 12208
You can store time when you app is to be terminated, one once the app is launched compare the last close date with current time, as such (goes to AppDelegate.swift):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let date = UserDefaults.standard.object(forKey: "TerminatedAt") as? Date {
let components = Calendar.current.dateComponents([.second], from: date, to: Date())
let numberOfSecondsSinceAppClosed = components.second ?? 0
}
return true
}
func applicationWillTerminate(_ application: UIApplication) {
UserDefaults.standard.set(Date(), forKey: "TerminatedAt")
UserDefaults.standard.synchronize()
}
Upvotes: 2