UNUserNotificationCenter. Notifications are not allowed for this application

3.8k views Asked by At

I noob in development application on OSX. I want to create app with Share extension. After content loading I want to show Notification, but I getting error "Notifications are not allowed for this application". I don't understand why requestAuthorization method not show dialog windows with permission, and how I can allow application to send notifications.

This is my code:

import Cocoa
import UserNotifications

class ShareViewController: NSViewController {
    override func loadView() {
        self.view = NSView()

        // Insert code here to customize the view
        let item = self.extensionContext!.inputItems[0] as! NSExtensionItem
        NSLog("Attachment = %@", item.attachments! as NSArray)
        showNotification()
        let outputItem = NSExtensionItem()
        let outputItems = [outputItem]
        self.extensionContext!.completeRequest(returningItems: outputItems, completionHandler: nil)
    }

    func showNotification() -> Void {
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.requestAuthorization(options: [.alert, .badge]) {
            (granted, error) in
            if granted {
                print("Yay!")
            } else {
                print("D'oh") // Print this, not authorized
            }
        }
        let content = UNMutableNotificationContent()

        content.title = "Hello"
        content.body = "This is example"
        content.sound = UNNotificationSound.default
        content.badge = 1
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        notificationCenter.add(request) { (error : Error?) in
            if let theError = error {
                print(theError) // Print Domain=UNErrorDomain Code=1 "Notifications are not allowed for this application"
            }
        }
    }
}
2

There are 2 answers

1
rusnasonov On

Apple does't allow send Notifications from Share extensions.

Documentation

1
paiego On

I don't see anywhere in the documentation that says you can't schedule new Local Notifications from an extension. I do however see an apple support ticket where someone had to deal with this issue, as do I.

Basically this failure is a race-condition. The key is to not call the contentHandler of this extension method:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

until after the completion handler of

notificationCenter.add(request: UNNotificationRequest>, withCompletionHandler: ((Error?) -> Void)

is called. It worked for me. Make sense?