Search code examples
iosswiftpush-notificationios10uilocalnotification

Schedule iOS Local Push Notification


let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound];
center.requestAuthorization(options: options) { (granted, error) in
    if !granted {
        print("Something went wrong")
    }
}
center.getNotificationSettings { (settings) in
    if settings.authorizationStatus != .authorized {
        // Notifications not allowed
    }
}
let content = UNMutableNotificationContent()
content.title = "Good Morning"
content.body = "wake up"
content.sound = UNNotificationSound.default()
var dateInfo = DateComponents()
dateInfo.hour = 7
dateInfo.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let identifier = "localNotification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
    if let _ = error {
        LOGG("Something went wrong")
    }
})

Above code, triggers push notification perfectly at 7 am. How I set notification at 9 pm or 12 pm using the same code. Thanks.


Solution

  • Try to fire at 9 PM

        var dateInfo = DateComponents()
        dateInfo.hour = 21
        dateInfo.minute = 0