2

I've searching and trying for too long how can I solve my problem. I have orders and I need to check for their updates on my backend C# per hour. Even on background state or foreground.

I have tried:

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)
}

Also:

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)
}

Also:

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)
}

And last that I cant put a timer:

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)
}

All of them doesn't print "background started" on background state, just on foreground. I added on info.plist:

<key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
    </array>
asr
  • 139
  • 3
  • 11
  • You are not going to be able to get something that runs in the background at an interval like that. Once your app goes into the background it will get suspended and if require can be terminated. – Upholder Of Truth Nov 14 '18 at 17:48

1 Answers1

2

You can try it using silent push notification. Every hour send 1 silent push notification and wake up the application in background mode and execute your task for some time.

You can read more detail for background task execution in below article:

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

Hardik Halani
  • 290
  • 2
  • 12