Reputation: 131
i want to send local notification when my application goes to background , the notification comes from calling web service (we couldn't use push notifications because we use local servers and there is no internet access) , i know about background fetch capability and i turned it on in my app but i want another timer to call the webservice every 2 minutes and push notifications if app doesn't terminated , anyone has an idea to do that?
Thanks
Upvotes: 1
Views: 3394
Reputation: 4391
Unfortunately push notifications from your server are the only way to have background tasks on a schedule that you decide.
Background fetch is for pulling data from a server so it is ready for the user when they open the app, but iOS decides when to use it based on when the user uses the app.
You can detect when the app is backgrounded and schedule a local notification then if necessary, but there is only a short amount of time to execute code before it will be suspended along with any timers you are trying to run.
You can detect when the app is going to the background in two ways:
Implement the applicationWillResignActive()
or UIApplicationDidEnterBackground()
methods in your app delegate.
Register for the UIApplicationDidEnterBackground
notification.
Here is an example of registering for the notification:
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(yourMethod), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
You can also check the app state at any time like this:
let state = UIApplication.shared.applicationState
if state == .background {
// App is in background
}
else if state == .active {
// App is in foreground
}
More information on extending background execution time, background app refresh and background modes.
Upvotes: 2