iosswiftnotificationsuilocalnotification

Is it possible to trigger an API call before displaying local notifications?


My project integrates a custom API which I wrote to retrieves data that I display on my app. I am also in the process of adding notifications. I am currently implementing local notifications and I am a bit in doubt on whether I can call the API before displaying the local notification. The reason I want to do this is because the database keeps changing with time and I would need to do a fresh query to fetch the new data.

Basically, what I want to do is call the api and get data to display for the notifications right before the scheduled notification is displayed. How can I go about achieving this? Has anybody done something similar?


Solution

  • You cannot guarantee anything, but you could implement background fetch and content-available pushes and have as fresh data as possible.

    There's a good write-up of the techniques here: https://layer.com/how-we-leverage-ios-push-notifications/

    Basically:

    1. If your app is killed or never run, there is nothing you can do to get data.
    2. If your app has been run, you could implement background fetches and then you get 30-second windows at non-deterministic times to get as up to date as you can.
    3. The server can send empty notifications with the content-available flag to try to trigger background fetches. If your data payloads are small, it can send that in the notification.

    You cannot schedule anything to happen at a specific time. The best you can do with local notifications is perhaps implement a custom view of it (iOS 10 feature) -- and in that view go get fresh data. You are in an extension when you do this, so it's not trivial.