Search code examples
swiftdatetimeuilocalnotification

Reoccurring local notification for UTC time


I looked all over stack overflow and was only able to find reoccurring local notifications for a specific time. However, I am trying to find information on how to make a reoccurring local notification based off a UTC time. The reason behind when you set up a reoccurring notification, it will stay to that specific time.

For example, at the moment 00:00:00 UTC is 5pm eastern time but when day light savings hits in a few months, the new time will be 4pm. However, the reoccurring notification is still set to 5pm. So this notification is now one hour off because of day light savings.

I am trying to figure out how to accomplish this, so the local notification will move properly with day light savings. I am not sure if this is possible since the reoccurring is set to a specific time, but I would love to find more information on this.


Solution

  • By default current Time Zone is considered for delivering local notifications. To use UTC time while registering for local notification, you need to set Time Zone to UTC.

    import UIKit
    import UserNotifications
    
    //get the notification center
    let center =  UNUserNotificationCenter.current()
    
    //create the content for the notification
    let content = UNMutableNotificationContent()
    content.title = " Title"
    content.subtitle = "SubTitle"
    content.body = "jvsvsvasvbasbvfasfv"
    content.sound = UNNotificationSound.default
    
    var dateComp = DateComponents()
    dateComp.timeZone = TimeZone(identifier: "UTC") // set time zone to UTC
    dateComp.day = 1;
    dateComp.hour = 08;
    dateComp.minute = 00;
    
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
    
    //create request to display
    let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)
    
    //add request to notification center
    center.add(request) { (error) in
        if error != nil {
            print("error \(String(describing: error))")
        }
    }
    

    Above code sets notification every morning 8 am UTC time.