我正在尝试在 func applicationDidEnterBackground
中运行代码,并希望将 timeDelay 设置为第二天凌晨 5 点。
IE:如果用户在 1 月 1 日晚上 10 点退出应用,我希望 timeDelay
是 1 月 2 日凌晨 5 点。
代码如下:
func applicationDidEnterBackground(_ application: UIApplication) {
submitBackgroundTasks()
}
func submitBackgroundTasks() {
// Declared at the "Permitted background task scheduler identifiers" in info.plist
let backgroundAppRefreshTaskSchedulerIdentifier = "bundle ID here"
let timeDelay = 10.0
do {
let backgroundAppRefreshTaskRequest = BGAppRefreshTaskRequest(identifier: backgroundAppRefreshTaskSchedulerIdentifier)
backgroundAppRefreshTaskRequest.earliestBeginDate = Date(timeIntervalSinceNow: timeDelay)
try BGTaskScheduler.shared.submit(backgroundAppRefreshTaskRequest)
print("Submitted task request")
} catch {
print("Failed to submit BGTask")
}
}
有什么建议吗?谢谢。
答案 0 :(得分:0)
第一步是将日期更改为第二天:
let changedDate = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
这将日期从 1 月 1 日晚上 10 点更改为 1 月 2 日晚上 10 点。我们有正确的日期,但我们需要将时间设置为凌晨 5 点:
let changedTimeAndDate = Calendar.current.date(bySettingHour: 5, minute: 0, second: 0, of: changedDate)!