【问题标题】:Receiving background notification in iOS using OneSignal使用 OneSignal 在 iOS 中接收后台通知
【发布时间】:2018-09-28 18:16:32
【问题描述】:

我正在使用 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
}

【问题讨论】:

    标签: ios iphone swift onesignal


    【解决方案1】:

    您需要在 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2016-12-24
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多