iosswiftnsdateformatterlocalnotificationunusernotificationcenter

Notification Wont Send If Time Contains "PM" - swift


I have some code that sends a notification at a certain time every day. The notification works for any time containing am. However, if the time contains pm the notification is not sent. I don't really know why though. Here is my code:

static func sendNotification(stringDate: String) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"

        let content = UNMutableNotificationContent()
        content.title = "Your daily news is ready!"
        content.body = "Come and check out the latest headlines!"

        if let date = dateFormatter.date(from: stringDate) {
            let calendar = Calendar.current

            let hour = calendar.component(.hour, from: date)
            let minute = calendar.component(.minute, from: date)

            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: "dateDone", content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
    }

in the function above I have a parameter called stringDate which is simply a string that contains the time I want to send the notification at. I don't really know the notifications only work in am so any help would be appreciated.


Solution

  • When using AM/PM you should use a different date format:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    

    If you don't have control over the input, you could first try to parse it in 24-hour format, and if that doesn't work with the AM/PM format