通知中心和更改时区
Notification Center and changing timezones
Swift 4 & >iOS 10.0
我想在特定日期和给定时间(比如下午 3 点)安排本地通知。我希望通知始终在下午 3 点触发,无论我在哪个时区(根据时区自动重新安排通知)。
以前,您可以调整 UILocalNotifications
' 时区来实现这一点,如 this SO post 中完美解释的那样。但是,在 >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
})
}
问题:
如何通过更改时区正确触发通知?
所以,我设法让它发挥作用。 triggerDate
有一个自动为 nil 的 timeZone 变量,就像 UILocalNotification
.
triggerDate.timeZone
的行为与 UILocalNotification.timeZone
完全相同(this post 中描述的行为与问题中提到的相同)。
它似乎在模拟器上不起作用的原因之一是因为我在更改时区时没有重新启动模拟器。重新启动将使一切按预期工作。
注意事项:也许重启不是强制性的,但由于 运行 模拟器检测新时区需要多长时间并不明显,我认为重启是最有效的解决方案。
Swift 4 & >iOS 10.0
我想在特定日期和给定时间(比如下午 3 点)安排本地通知。我希望通知始终在下午 3 点触发,无论我在哪个时区(根据时区自动重新安排通知)。
以前,您可以调整 UILocalNotifications
' 时区来实现这一点,如 this SO post 中完美解释的那样。但是,在 >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
})
}
问题: 如何通过更改时区正确触发通知?
所以,我设法让它发挥作用。 triggerDate
有一个自动为 nil 的 timeZone 变量,就像 UILocalNotification
.
triggerDate.timeZone
的行为与 UILocalNotification.timeZone
完全相同(this post 中描述的行为与问题中提到的相同)。
它似乎在模拟器上不起作用的原因之一是因为我在更改时区时没有重新启动模拟器。重新启动将使一切按预期工作。
注意事项:也许重启不是强制性的,但由于 运行 模拟器检测新时区需要多长时间并不明显,我认为重启是最有效的解决方案。