Ste*_*ker 4 macos notifications swift xcode8
我尝试将横幅通知生成器添加到我的 macOS swift 应用程序中,但在 XCode 中运行测试时,横幅没有出现,并且通知中心中也没有任何新通知可见。我计算机上的其他应用程序会定期生成通知。我错过了什么?我已按要求授予许可
我的应用程序委托如下
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
@IBOutlet weak var mainMenu: NSMenu!
func applicationDidFinishLaunching(_ aNotification: Notification)
{
NSUserNotificationCenter.default.delegate = self ;
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool
{
return true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
Run Code Online (Sandbox Code Playgroud)
在应用程序启动时,我运行以下方法,并看到控制台行“允许通知”
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])
{ granted, error in
if error != nil
{
print ("Request notifications permission Error");
};
if granted
{
self.allowNotifications = true ;
print ("Notifications allowed");
}
else
{
self.allowNotifications = false ;
print ("Notifications denied");
};
}
Run Code Online (Sandbox Code Playgroud)
我添加到我的ViewController中的方法如下,我已经测试到达了最后的打印语句
func generateNotification (summary:String, sound:String, title:String , body:String)
{
let notification = NSUserNotification()
if !allowNotifications {return};
notification.title = summary ;
notification.subtitle = title ;
notification.informativeText = body ;
if (sound == "YES") {notification.soundName = NSUserNotificationDefaultSoundName};
NSUserNotificationCenter.default.deliver (notification);
print ("notification generated");
};
Run Code Online (Sandbox Code Playgroud)
请帮我
我相信我的问题是请求使用 UNUserNotification 的权限,然后使用 NSUserNotification 创建通知本身,当然我没有请求使用权限。现在,在 Catalina 中请求许可是强制性的(也许在早期版本的 macOS 中也是如此。)
因此,我用以下代码替换了generateNotification函数,并且一切正常。
let notificationCenter = UNUserNotificationCenter.current();
notificationCenter.getNotificationSettings
{ (settings) in
if settings.authorizationStatus == .authorized
{
//print ("Notifications Still Allowed");
// build the banner
let content = UNMutableNotificationContent();
content.title = summary ;
content.body = title ;
if sound == "YES" {content.sound = UNNotificationSound.default};
// could add .badge
// could add .userInfo
// define when banner will appear - this is set to 1 second - note you cannot set this to zero
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false);
// Create the request
let uuidString = UUID().uuidString ;
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger);
// Schedule the request with the system.
notificationCenter.add(request, withCompletionHandler:
{ (error) in
if error != nil
{
// Something went wrong
}
})
//print ("Notification Generated");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3977 次 |
| 最近记录: |