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

Local Notifications make sound but do not display (Swift)

我正在尝试使用 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")
   }
}

访问请求:

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 秒后应用发出默认声音但不显示警报内容。我正在尝试在前台和后台使用该应用程序。

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

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

添加此协议 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])
        }
    }

我遇到了同样的问题。

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

所以解决方案是确保您的内容 body 不是空字符串。