通知中心和更改时区

sta*_*set 2 swift unusernotificationcenter swift4

斯威夫特 4 & >iOS 10.0

我想在特定日期和给定时间(比如下午 3 点)安排本地通知。我希望通知总是在下午 3 点发出,无论我在哪个时区(根据时区自动重新安排通知)。

以前,您可以调整UILocalNotifications“时区”来实现这一点,就像这篇 SO 帖子中完美解释的那样。但是,在>iOS 10.0,UILocalNotifications已弃用。

这是我的代码:

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
    })
  }
Run Code Online (Sandbox Code Playgroud)

问题: 如何使通知在时区变化时正确触发?

sta*_*set 5

所以,我设法让它工作。在triggerDate具有时区变量这是自动零,酷似UILocalNotification

triggerDate.timeZone行为完全一样UILocalNotification.timeZone这篇文章中描述的行为,与问题中提到的相同)。

它似乎在模拟器上不起作用的原因之一是因为我在更改时区时没有重新启动模拟器。重新启动将使一切按预期工作。

注意:也许重启不是强制性的,但由于运行模拟器检测新时区需要多长时间并不明显,我认为重启它是最有效的解决方案。