简体   繁体   中英

Handling iOS push notifications when the app is not running

I have an app that receives PN from a backend using Firebase Cloud Messaging. Basically, all I what to do is store some data of the PN with CoreData. I'm using application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) to do it. I tested the feature in foreground and background, opening the app with the PN and with the app icon. Everything works fine. But the problem is in this two cases:

  • When the app is killed, a PN arrives, and the user taps on the push notification.
  • When the app is killed, a PN arrives, and the user taps on the app icon.

I saw that sometimes, didReceiveRemoteNotifications is fired. Sometimes, it doesn't. I read that this method is not called when the app is killed but I'm experiencing a different behaviour. Also, I read that the way to handle push notifications in killed state is with VoIP apps or with UNNotificationServiceExtension . My app is not a VoIP app… Anyone knows if UNNotificationServiceExtension can resolve my problem? This is the payload fired by the backend:

const message = {
  apns: {
    payload: {
      aps : {
        'content-available' : 1,
        alert: {
          title : "Game Request",
          body : "Bob wants to play poker",
        }
     },
    },
  },
  data: {
    shortText: 'test',
    chasisNumber: '23',
    alertType: 'some alert type',
    alertId: '1234',
    alertTypeId: '1234',
    userId: '1234',
    text: 'some text',
    title: 'some title',
    deleted: 'false',
    creationDate: '2011-11-02T02:50:12.208Z',
    receivedDate: '2011-11-02T02:50:12.208Z',
    actionType: 'some action type',
    ticketId: '1234',
    status: 'some status'
  },
  tokens: [androidToken, iosToken]
};

First of all to answer your question before iOS 13 is that it was possible to handle a push via VoIP. Since iOS13 this method is no longer possible.

If your application is killed it is not possible to handle the push notification if the user does not click on the notification. If you receive a PN and the user opens the application via the phone's home screen you will not be able to access the PN data.

  • If the application is killed, the user receive PN and he click on the notification to open the app; you must add the below code in the method didFinishLaunchingWithOptions of the AppDelegate to handle the PN:
if let remoteUserInfo = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
    self.application(application, didReceiveRemoteNotification: remoteUserInfo)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM