Swift中获取App上次打开时间

在日常开发中,我们经常会遇到一些情况,需要获取用户上次打开App的时间。

这里介绍一个最简单的方法,以macOS为例:

首先我们需要在App退出之前保存当前时间

1
2
3
4
5
6
7
8
9
10
11
12
// In AppDelegate

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

// OR

func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
UserDefaults.standard.set(Date(), forKey: "LastOpened")
}

然后在App下次启动的时候去获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// In AppDelegate

func applicationDidBecomeActive(_ notification: Notification) {
guard let lastOpened = UserDefaults. standard. object(forKey: "LastOpened") as? Date else { return }

let elapsed = Calendar.current.dateComponents([.day], from: tastOpened, to: Date())
if elapsed.day! >= 1 { // Do your logics
// show alert
}
}

// OR

func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the popover and set the content view.

// 以上相同
}

That’s it! iOS同理。


不足之处,欢迎指正。


Swift中获取App上次打开时间
https://royrao2333.github.io/blog/Swift/Swift中获取App上次打开时间/
作者
Roy Rao
发布于
2022年11月30日 凌晨
许可协议