Local Notifications make sound but do not display (Swift)

ⅰ亾dé卋堺 提交于 2019-12-01 04:44:25

问题


I am trying to create a local notification for my app using Apple's UNUserNotificationCenter.

Here is my code:

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")
   }
}

Access Request:

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")
   }
}

After 5 seconds the app makes the Default sound but does not show the alert content. I am trying both with the app in the foreground and in the background.


回答1:


I had the same problem.

If your content body is blank ie(content.body == "") then you won't get a notification even if you do have a title.

So the solution is to make sure that your content body is not an empty string.




回答2:


Add this Protocoal UNUserNotificationCenterDelegate. and add this delegate into your controller. and dont forget to set delegate.

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])
        }
    }



回答3:


Add this code into didFinishLaunchingWithOption in AppDelegate.swift file

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


来源:https://stackoverflow.com/questions/42431171/local-notifications-make-sound-but-do-not-display-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!