This question is an update to some outdated questions like:
how to call function after every 1 hour?(Swift). Background fetch work when app is terminated?
Sending Latitude and Longitude to Server when app is in background
...
I'm currently developing an simple mobile application for iOS by using Swift 4.
It's a messenger app like e.g. WhatsApp
and because new messages must be delivered instantly the application must be able to check for new messages for the Users via Json request every minute.
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask { endBackgroundTask() }
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
Till now - when the app is in background-mode after about 2 minutes the app is terminating, the getnewmessages-timer interval
is stopping and it prints out "Background task ended"
.
How to use Swift to register an infinite-running timer (background-fetching) that calls the update messages function?
iOS background fetch for: An app that downloads and process new content regularly --> My messenger app