我在OSX上的开发应用程序中有菜鸟。我想使用Share extension创建应用。加载内容后,我想显示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"
}
}
}
}
答案 0 :(得分:1)
我在文档中什么都看不到,说您无法通过扩展程序安排新的本地通知。但是,我在see an apple support ticket的地方也要像我一样处理这个问题。
基本上,此故障是竞争条件。关键是不调用此扩展方法的contentHandler:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
直到
的完成处理程序notificationCenter.add(request: UNNotificationRequest>, withCompletionHandler: ((Error?) -> Void)
被调用。它为我工作。有道理吗?
答案 1 :(得分:0)
Apple不允许通过共享扩展程序发送通知。