I need to create a local UserNotification every-time the application does a background fetch or does a sync with a bluetooth device. The problem is that the old Local Notifications before iOS 10 worked and now the new UserNotifications they don't work/trigger, nothing happens. Is there any solution regarding this problem?
Currently my testing code is the following:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
print("NOT authorized")
}
}
let content = UNMutableNotificationContent()
content.title = "MyApp"
content.body = "oi"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
let notification = UNNotificationRequest(identifier: "timer", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(notification) { (error) in
if error != nil {
print("DID NOT CREATE NOTIFICATION")
}else{
print("CREATED NOTIFICATION")
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: > @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, > >didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
} }
Ok, I found the problem, I was missing the request authorisation code.
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}