oyalhi oyalhi - 1 month ago 52
iOS Question

Manuel in-app notification alert using OneSignal iOS10

I have setup the OneSignal so that it shows iOS 10 default in-app notification. However, in some cases the in-app notification should no be shown. E.g. if the user is already on the same page as the info in the notification.

How can I show the default iOS 10 in-app notification manually using OneSignal?

Here is my code:

OneSignal.initWithLaunchOptions(launchOptions, appId: "your-app-id-here", handleNotificationReceived: ({ (notification) in
}), handleNotificationAction: ({ (result) in
LGNotificationHandler.handleNotificationAction(result: result)
}), settings: [
kOSSettingsKeyAutoPrompt: false,
kOSSettingsKeyInAppAlerts: false,
kOSSettingsKeyInFocusDisplayOption: OSNotificationDisplayType.notification.rawValue])


In appdelegate where you need to set the in-app alerts to true. p.s. DLog is used just for logging in debug mode, can be ignored.

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

    // MARK: - OneSignal Notifications
    OneSignal.initWithLaunchOptions(launchOptions, appId: "your-app-id-here", handleNotificationReceived: ({ (notification) in
        DLog("handleNotificationReceived: \(notification)")
    }), handleNotificationAction: ({ (result) in            
        DLog("handleNotificationAction: \(result)")
    }), settings: [
        kOSSettingsKeyAutoPrompt: false,
        kOSSettingsKeyInAppAlerts: true,
        kOSSettingsKeyInFocusDisplayOption: OSNotificationDisplayType.none.rawValue

    // You will get a warning here if you are using the latest OneSignal library, but can be safely ignored for the time being.

    DLog("--- appDelegate end")
    return true

In the delegate, you can set individual options, then you need to call completionHandler(options) as shown below:

// =========================================================================
// MARK: - OSUserNotificationCenterDelegate
extension AppDelegate: OSUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: Any!, willPresentNotification notification: Any!, withCompletionHandler completionHandler: ((UInt) -> Swift.Void)!) {
        // set the options here
        var options: UInt = 0

        options |= UNNotificationPresentationOptions.badge.rawValue  // if you want to show the badge number
        options |= UNNotificationPresentationOptions.alert.rawValue  // if you want to show alert dialog box
        options |= UNNotificationPresentationOptions.sound.rawValue  // if you want notification to play sound

        // here we perform the notifications