Despite spending literally days on this code I still cannot get it to trigger as it should. Have looked at many recent tutorials online and my code matches them all but will still not behave as it should on building to either simulator or device. All I want is the Local Notification to trigger on a certain time each day (code shown attempted 10:12 am). Deployment Target is iOS 14.3 and I am using latest swift 5. In desperation I have even tried to use the time interval UNTimeIntervalNotificaitonTrigger method to create the span of time into the next day but this tests very sporadically on both device and simulator (sometimes triggering in seconds or minutes) However, I would ideally like it firing on a certain time each day.
I have not coded anything in appDelegate or sceneDelegate because the tutorials that I have followed did not at all. All of this code is is the viewDidLoad of the ViewController that I want the notification to be authorised from (This is not the Initial View Controller if that makes a difference). Begging for Help!
//STEP 1 - Ask user for permission to notify
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
// TO REMOVE NOTIFICAITONS: UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
print("All set with User Authorisation!")
} else if let error = error {
print("Oh No, Authorisation did not work: ", error.localizedDescription)
}
}
//STEP 2 - Create Notification Content
let content = UNMutableNotificationContent()
content.title = "Daily Notification TITLE"
content.subtitle = "Hey - this is your daily notification SUBTITLE"
content.body = "This is the BODY of your daily notification"
content.sound = UNNotificationSound.default
//STEP 3 - Set up the Trigger by time each day
var triggerTime = DateComponents()
triggerTime.hour = 10
triggerTime.minute = 12
let myNotificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)
// STEP 4 - Creating the Request
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: myNotificationTrigger)
// Step 5 - Register the Request
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error{
print("Error has occured: \(error.localizedDescription)")
} else {
print("Added Notification: \(UUID().uuidString)")
}
}
} // END OF THE viewDidLoad bracket