please i have an issue about how can i trigger the local notification at specific time ? without user trigger it and need the app at specific time fired local notification
the following my code :
this is for get permission from the user
func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
}
// this i schedule local notification func scheduleLocal() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.hour = 3
dateComponents.minute = 19
dateComponents.day = 3
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
center.removeAllPendingNotificationRequests()
}
// her i call theses methods
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerLocal()
scheduleLocal()
return true
}
and when i close my app i have no receive the notification , please help about how can i trigger the local notification at specific time
thanks
You should not call
center.removeAllPendingNotificationRequests()after adding your notification, since it will cancel the previously added pending notification as well. You should rather check after callingcenter.addRequest(request)whether your request has actually been added or not byOr you can also specify a completion handler to
addRequest, which will return an error if the request hasn't been added succesfully: