iOS-与时区无关的本地通知

时间:2018-10-15 16:08:09

标签: ios swift uilocalnotification

我在iOS中遇到本地通知问题。 我想在某个时间安排通知,但是无论时区如何,都必须将其触发...即:如果我在03:00 PM安排通知,则无论我身在何处,通知都必须在03:00 PM触发。 .. 这是我的代码,但我无法达到此结果...您能帮我吗? 谢谢!

static func createNotificationNamed(_ notificationName: String, at notificationDate: Foundation.Date, title: String, body: String, delta: UInt32) {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            if granted {
                let calendar = Calendar(identifier: .iso8601)
                var components = calendar.dateComponents(in: .current, from: notificationDate)
                components.minute = components.minute! + Int(arc4random_uniform(delta))

                var datecomp = DateComponents()
                datecomp.year = components.year
                datecomp.month = components.month
                datecomp.day = components.day
                datecomp.hour = components.hour
                datecomp.minute = components.minute
                datecomp.calendar = components.calendar
                datecomp.timeZone = TimeZone.autoupdatingCurrent

                let trigger = UNCalendarNotificationTrigger(dateMatching: datecomp, repeats: false)
                let content = UNMutableNotificationContent()
                content.title = title
                content.body = body
                content.sound = UNNotificationSound.default()

                let request = UNNotificationRequest(identifier: notificationName, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request) {(error) in
                    if let error = error {
                        print("Uh oh! We had an error: \(error)")
                    }
                }
            }
        }
    }
}

为了模拟它,我安排了通知时间,然后在手机上更改TimeZone,然后等待正确的时间,但是什么也没发生。

2 个答案:

答案 0 :(得分:0)

尝试使用此功能并传递您的日期,还可以对AppDelegate文件授予本地通知权限,还可以明智地检查本地权限iOS版本。

func scheduleNotification(date: Date) {

    var dateComponents: DateComponents = DateComponents()

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

    dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)

    let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: notificationTrigger)

    let notiCurrent = UNUserNotificationCenter.current()
    notiCurrent.add(request) { (error) in
        if let error1 = error {
            print(error1.localizedDescription)
        }
    }

}

答案 1 :(得分:0)

最后,我通过设置特定的TimeZone解决了这个问题...

datecomp.timeZone = TimeZone.init(abbreviation: "PDT")