5

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

4

3 回答 3

15

我有同样的问题。

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

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

于 2017-05-19T10:22:57.930 回答
2

添加此协议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])
        }
    }
于 2017-02-24T06:03:31.987 回答
0

将此代码添加到didFinishLaunchingWithOptionAppDelegate.swift 文件中

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) 
{ (granted, error) in
// Enable or disable features based on authorization.
}
于 2017-02-24T05:15:34.223 回答