使用OneSignal在iOS中接收后台通知

时间:2018-09-28 18:16:32

标签: ios iphone swift onesignal

我正在使用swift创建一个iOS应用。我已经集成了onesignal SDK来进行推送通知。现在,当应用程序处于前台时,我可以接收和管理通知。当应用程序在后台运行时,我可以在通知面板中接收通知,但是我无法在appdelegate中接收通知并进行管理。在appdelegate中,当应用程序在后台运行时,我可以在哪里收到通知?我正在共享我的代码。我应该更改有效载荷中的任何内容吗?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in

      print("Received Notification: \(notification!.payload.notificationID)")
   }

   let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
      // This block gets called when the user reacts to a notification received
      let payload: OSNotificationPayload = result!.notification.payload

      var fullMessage = payload.body
      print("Message = \(fullMessage)")

      if payload.additionalData != nil {
         if payload.title != nil {
            let messageTitle = payload.title
               print("Message Title = \(messageTitle!)")
         }

         let additionalData = payload.additionalData
         if additionalData?["actionSelected"] != nil {
            fullMessage = fullMessage! + "\nPressed ButtonID: \(additionalData!["actionSelected"])"
         }
      }
   }

   let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false,
      kOSSettingsKeyInAppLaunchURL: true]

   OneSignal.initWithLaunchOptions(launchOptions, 
      appId: ONESIGNALAPP_I", 
      handleNotificationReceived: notificationReceivedBlock, 
      handleNotificationAction: notificationOpenedBlock, 
      settings: onesignalInitSettings)

   OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification

   return true
}

1 个答案:

答案 0 :(得分:0)

您需要在AppDelegate中实现以下方法:

extension AppDelegate {

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        //use response.notification.request.content.userInfo to fetch push data
    }

    // for iOS < 10
    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        //use notification.userInfo to fetch push data
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        //use userInfo to fetch push data
    }
}