2

我在 OSX 上的开发应用程序中是新手。我想创建带有共享扩展的应用程序。内容加载后,我想显示Notification,但出现错误“此应用程序不允许通知”。我不明白为什么requestAuthorization方法不显示具有权限的对话框窗口,以及如何允许应用程序发送通知。

这是我的代码:

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"
            }
        }
    }
}
4

2 回答 2

1

我在文档中没有看到任何地方说您无法从扩展程序安排新的本地通知。然而,我确实看到了一张苹果支持票,有人必须处理这个问题,我也是。

基本上,这种失败是一种竞争条件。关键是不要调用这个扩展方法的contentHandler:

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

直到完成处理程序之后

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

叫做。它对我有用。有道理?

于 2020-05-12T00:36:11.827 回答
-2

Apple 不允许从共享扩展发送通知。

文档

于 2019-10-18T18:37:46.713 回答