本地通知声音,但不显示(Swift)

我正在尝试使用Apple的UNUserNotificationCenter为我的应用程序创build本地通知。

这是我的代码:

let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = task.name content.body = task.notes content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: task.UUID, content: content, trigger: trigger) center.add(request) { (error:Error?) in if let theError = error { print("Notification scheduling error: \(error)") }else{ print("Notification was scheduled successfully") } } 

访问请求:

 let center = UNUserNotificationCenter.current() //request notification access let options: UNAuthorizationOptions = [.alert, .sound] center.requestAuthorization(options: options) { (granted, error) in if !granted { print("Notification access was denied") } } 

5秒钟后,应用程序发出默认声音,但不显示警报内容。 我正在尝试在前台和后台的应用程序。

我有同样的问题。

如果你的内容主体是空白ie(content.body ==“”),那么即使你有一个标题,你也不会收到通知。

所以解决scheme是确保您的内容正文不是一个空string。

将此代码添加到AppDelegate.swift文件中的didFinishLaunchingWithOption

 let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } 

添加这个Protocoal UNUserNotificationCenterDelegate 。 并将此代理添加到您的控制器。 不要忘记设置代表。

 UNUserNotificationCenter.current().delegate = self func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("Notification being triggered") //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10 //to distinguish between notifications if notification.request.identifier == "yourrequestid"{ completionHandler( [.alert,.sound,.badge]) } }