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

Mat*_*ler 4 ios swift unnotificationrequest

我正在尝试使用Apple的UNUserNotificationCenter为我的应用创建本地通知.

这是我的代码:

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")
   }
}
Run Code Online (Sandbox Code Playgroud)

访问请求:

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")
   }
}
Run Code Online (Sandbox Code Playgroud)

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

365*_*uns 13

我有同样的问题.

如果您的内容正文为空(即content.body ==""),那么即使您拥有标题,也不会收到通知.

因此,解决方案是确保您的内容正文不是空字符串.

  • 只是一个观察:iOS 10.3 (10.x?) 中的本地通知要求设置内容正文以显示警报。但在 iOS 11.x 中,不需要内容正文。但您必须指定以下 3 项之一:标题、副标题或正文。 (2认同)