我已经搜索并尝试了太长时间,如何解决我的问题。 我有订单,需要每小时在我的后端 C# 上检查它们的更新。即使在后台状态或前台。
我已经尝试过:
var timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
timer in
self.updatePedidos(timer: timer)
}
func updatePedidos() {
print("background started")
let strdata = Functions.getMostRecentDtPedido()
Functions.loadOrdersFromLastSyncByApi(strdata)
}
另外:
func applicationDidEnterBackground(_ application: UIApplication) {
Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.updatePedidos), userInfo: nil, repeats: true)
}
@objc func updatePedidos() {
print("background started")
let strdata = Functions.getMostRecentDtPedido()
Functions.loadOrdersFromLastSyncByApi(strdata)
}
另外:
func applicationDidEnterBackground(_ application: UIApplication) {
UIApplication.shared.setMinimumBackgroundFetchInterval( 5 )
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler:
@escaping (UIBackgroundFetchResult) -> Void) {
print("background started")
let strdata = Functions.getMostRecentDtPedido()
Functions.loadOrdersFromLastSyncByApi(strdata)
if let newData = fetchUpdates() {
addDataToFeed(newData: newData)
completionHandler(.newData)
}
completionHandler(.noData)
}
最后我不能设置计时器:
NotificationCenter.default.addObserver(self, selector: #selector(updatePedidos), name:UIApplication.didEnterBackgroundNotification, object: nil)
@objc func updatePedidos() {
print("background started")
let strdata = Functions.getMostRecentDtPedido()
Functions.loadOrdersFromLastSyncByApi(strdata)
}
所有这些都不会在后台状态下打印“后台启动”,而只是在前台打印。我在 info.plist 上添加了:
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
</array>
最佳答案
您可以使用静默推送通知来尝试。每小时发送 1 条静默推送通知,并在后台模式下唤醒应用程序并执行您的任务一段时间。
您可以在下面的文章中阅读有关后台任务执行的更多详细信息:
https://www.hackingwithswift.com/example-code/system/how-to-run-code-when-your-app-is-terminated
Is there a way to wakeup suspended app in iOS without user or server intervention
关于swift - 每小时安排后台任务 swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304770/