【发布时间】:2018-07-02 12:10:57
【问题描述】:
我想在每天的固定时间运行一个函数(进行 api 调用),比如每天上午 10 点和晚上 10 点。 swift 中的 cronjob 等价物是什么?
我尝试将 Timer 实现为:
var dateComponents = DateComponents()
dateComponents.timeZone = TimeZone(abbreviation: "NPT")
dateComponents.hour = 10
dateComponents.minute = 00
let userCalendar = Calendar.current
let myTime = userCalendar.date(from: dateComponents)
let timer = Timer(fireAt: myTime!, interval: 0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
选择器功能:
@objc func updateTimer() {
print("Hello")
}
选择器函数不是在指定时间运行,而是在我每次运行应用程序时执行,而不是在指定时间执行。我该如何解决这个问题?
编辑:我也需要从后台运行它。我将在我的应用中使用定位服务。
【问题讨论】:
-
我已经编辑了问题:我也需要在后台
-
iOS 没有等效的 cron。您可以安排本地通知,但如果应用程序不在前台,则它不会运行。唯一支持的用于定期获取数据的后台模式是 Background Fetch,但 iOS 决定运行它的频率,而不是您
-
@NishuPriya “应用程序未打开”和“应用程序在后台”是不同的东西,请区分一下。
-
@Scriptable 我正在使用标准位置服务在应用程序中获取位置更新(应用距离过滤器,禁用暂停位置更新)并启用后台模式。定时器不是继续在后台运行吗?