Shyam
Shyam

Reputation: 571

Using UNUserNotificationCenter to support iOS 10 rich notifications, but the notification never shows up. It only sounds the alert

Not sure, what's missing, but I'm stuck with a weird problem!!!

Notification sounds, but isn't displayed.

I have registered the app to only display alerts and sounds, and strangely it never is displayed. I can see that the notification is added successfully. But, there seems to be something trivial that I'm not able to comprehend.

Even removing the notification works.

import Foundation
import NotificationCenter
import UserNotifications

class NotificationManager: NSObject {

    private let categoryIdentifier = "notificationCategory"

    private var toDateComponents = NSDateComponents()

    private enum actionIdentifier : String {
        case openApp = "openApp"
        case playMusic = "playMusic"
    }

    // MARK: - Register for notifications

    func registerForNotifications(application: UIApplication) {
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler { notificationSettings in
                switch notificationSettings.authorizationStatus {
                case .NotDetermined:
                    UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Alert, .Sound]) { (granted, error) in
                        // Enable or disable features based on authorization
                        if granted {
                            print("Access requested and was granted for sending notifications")
                            UNUserNotificationCenter.currentNotificationCenter().setNotificationCategories([])
                            UNUserNotificationCenter.currentNotificationCenter().delegate = self
                            self.setupNotificationActions()
                        } else {
                            print("Access requested and was denied for sending notifications")
                            print(error?.localizedDescription)
                        }
                    }
                case .Denied:
                    print("Notifications are turned off!!")
                break // nothing to do, pointless to go on
                case .Authorized:
                    self.setupNotificationActions()
                }
            }
        } else {
            // Nothing to do here
            print("iOS 9 says, Let's get started...")
            self.setupNotificationActions()
        }
    }

    // MARK: - Setup notification actions

    private func setupNotificationActions() {

        // Initialize and specify the notification actions
        if #available(iOS 10.0, *) {
            let openAppAction = UNNotificationAction(identifier: actionIdentifier.openApp.rawValue, title: "Open App", options: [.AuthenticationRequired, .Foreground])
            let playMusicAction = UNNotificationAction(identifier: actionIdentifier.playMusic.rawValue, title: "Play Music", options: [])
            let notificationCategory = UNNotificationCategory(identifier: categoryIdentifier, actions: [openAppAction, playMusicAction], intentIdentifiers: [], options: [.CustomDismissAction])

            UNUserNotificationCenter.currentNotificationCenter().setNotificationCategories([notificationCategory])
        } else {
            // Specify the notification actions
            let openAppAction = UIMutableUserNotificationAction()
            openAppAction.identifier = actionIdentifier.openApp.rawValue
            openAppAction.title = "Open App"
            openAppAction.activationMode = UIUserNotificationActivationMode.Foreground
            openAppAction.destructive = false

            let playMusicAction = UIMutableUserNotificationAction()
            playMusicAction.identifier = actionIdentifier.playMusic.rawValue
            playMusicAction.title = "Play Music"
            playMusicAction.activationMode = UIUserNotificationActivationMode.Background
            playMusicAction.destructive = false
            playMusicAction.authenticationRequired = false

            // Specify the category related to the above actions
            let notificationCategory = UIMutableUserNotificationCategory()
            notificationCategory.identifier = categoryIdentifier
            notificationCategory.setActions([openAppAction, playMusicAction], forContext: UIUserNotificationActionContext.Default)
            notificationCategory.setActions([playMusicAction], forContext: UIUserNotificationActionContext.Minimal)

            let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: NSSet(object: notificationCategory) as? Set<UIUserNotificationCategory>)
//            if (notificationSettings.types != UIUserNotificationType.None){
                UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
//            }
        }
    }

And, in AppDelegate...

private let notificationManager = NotificationManager()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    notificationManager.registerForNotifications(application)
}

Upvotes: 2

Views: 1794

Answers (2)

Tamojit Pal
Tamojit Pal

Reputation: 111

Whenever are you sending rich notification be sure about payload, must contain "mutable-content": 1,

payload like,

{
  "aps": {
    "alert": "Test Rich Notification",
    "mutable-content": 1,
    "badge": "1"
  },
  "mediaUrl": "https://www.awaragroup.com/wp-content/uploads/2015/05/it-specialist.jpg",
  "mediaType": "jpg"
}

Upvotes: 4

Shyam
Shyam

Reputation: 571

Delegate should be assigned correctly. Although, I wasn't able to zero in on why this happened, below changes ensured that notifications went through.

AppDelegate,

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    private let notificationManager = NotificationManager()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UNUserNotificationCenter.currentNotificationCenter().delegate = self
    notificationManager.registerForNotifications()

    }
}

Insert the delegate methods in AppDelegate, itself.

Upvotes: 1

Related Questions