Notification Center and changing timezones

点点圈 提交于 2019-12-11 04:03:29

问题


Swift 4 & >iOS 10.0

I want to schedule a local notification at a certain date and at a given time (let's say 3PM). I want the notifications to always be fired at 3PM, whatever the timezone I am in (automatic rescheduling of notifications according to timezones).

Previously, you could tweak UILocalNotifications' time zone to achieve exactly this, like perfectly explained in this SO post. However, in >iOS 10.0, UILocalNotifications is deprecated.

Here is my code:

func scheduleNotification(title: String, message: String, atDate: Date){

    let center = UNUserNotificationCenter.current()

    // Create content
    let content = UNMutableNotificationContent()
    content.title = title
    content.body = message
    content.sound = UNNotificationSound.default()

    // Create trigger
    let calendar = Calendar(identifier: .gregorian)
    let triggerDate = calendar.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: atDate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)

    // Create identifier
    let identifier = "\(UUID())"

    // Create request & add to center
    let request = UNNotificationRequest(identifier: identifier,
                                        content: content,
                                        trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
    })
  }

Question: How do you make the notification triggers properly with changing timezones ?


回答1:


So, I managed to make it work. The triggerDate has a timeZone variable which is automatically nil, exactly like UILocalNotification.

triggerDate.timeZone behaves exactly like UILocalNotification.timeZone (behaviour described in this post, the same as mentioned in the question).

One of the reason it did not seem to work on the simulator was because I was not restarting the simulator when changing the timezone. Restarting will make everything work as expected.

Nota bene: Maybe a restart is not mandatory but since it's not obvious how much time a running simulator will take to detect the new timezone, I think restarting it is the most efficient solution.



来源:https://stackoverflow.com/questions/47327446/notification-center-and-changing-timezones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!