John Sorensen
John Sorensen

Reputation: 960

How to format FCM json for background notifications iOS

I'm struggling to find references that discuss how exactly to structure my message .jsons for background-notifications in FCM. I have tried various configurations, but right now I have this:

const message = {
    notification: {
        title: "Title",
    },
    apns: {
        payload: {
            aps: {
                'contentAvailable': 1
            }
        },
    },
    token: registrationToken,
};

I want this message to show up as a notification--i.e. for the user to see it--but I also want to trigger:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

}

So I can perform data updates if the app is in background mode. I am able to see this notification, but that function isn't triggered when the notification arrives--so no data refresh is possible. How can I format my FCM .json to enable this?

Upvotes: 1

Views: 3135

Answers (2)

KafKafOwn
KafKafOwn

Reputation: 545

You got payload and headers, payload should contain content_available = 1(not contentAvailable, other than that you are fine) and headers should have "apns-push-type" = "background" and "apns-priority" = "5"

public class ApnsConfig {
    @Key("headers")
    private final Map<String, String> headers;
    @Key("payload")
    private final Map<String, Object> payload;
    @Key("fcm_options")
    private final ApnsFcmOptions fcmOptions;
}

Apple Documentation

Upvotes: 0

Ido
Ido

Reputation: 697

First thing, according to apple documentation, the key contentAvailable that you are using should actually be content-available, so without fixing this, the application(_:didReceiveRemoteNotification:fetchCompletionHandler:) function wouldn't be triggered anyway.

Now, FCM have an example of how the .json file should look like, so for your data it should be something like this:

const message = {
  "aps" : {
    "alert" : {
      "title" : "Title"
    },
    "badge" : 1,
    "content-available": 1
  },
  "token" : registrationToken
}

Now I guess you'd like to customize the notification a bit more (for example adding body, subtitle etc.), so you may find the full list of keys organized in tables in the article Generating a Remote Notification.

Upvotes: 1

Related Questions