swift - 每小时安排后台任务 swift 4

标签 swift background task schedule

我已经搜索并尝试了太长时间,如何解决我的问题。 我有订单,需要每小时在我的后端 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/

相关文章:

ios - 跟随玩家时 SpriteKit 相机卡顿

iphone - UIView背景图案

ios - 如何在iOS cocos2d中无限移动背景图片

java - Infinispan分布式任务执行

c# - 既然可以直接返回 Task<T>,为什么还要使用 async 并返回 await?

ios - 知道另一个应用程序的 bundle id,可能会破解钥匙串(keychain)访问?

json - 读取 JSON "not an object"

ios - 在不耗尽电池电量的情况下以良好的准确性获取位置更新的最佳方法

html - 如何在 CSS 中旋转背景?

c# - 在C#中获取已执行任务的统计信息