sajith kannan
sajith kannan

Reputation: 145

Receiving background notification in iOS using OneSignal

I am creating an iOS app using swift. I have integrated onesignal SDK for push notification. Now i can receive and manage notification when the app is in foreground. when the app is in background,i can receive notification in notification panel,but i cannot receive it and manage in appdelegate.In appdelegate where can i receive notifiation when the app is in background?Here i am sharing my code. Should i change anything in payload?

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
}

Upvotes: 1

Views: 1961

Answers (1)

Hasti Ranjkesh
Hasti Ranjkesh

Reputation: 671

You need to implement these methods in 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
    }
}

Upvotes: 2

Related Questions