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.
Add this Protocoal
UNUserNotificationCenterDelegate
. and add this delegate into your controller. and dont forget to set delegate.Add this code into
didFinishLaunchingWithOption
in AppDelegate.swift fileI 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.