我已经搜索并尝试了太长时间,该如何解决我的问题。 我有订单,我需要每小时在后端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>
答案 0 :(得分:0)
您可以使用静默推送通知进行尝试。每小时发送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