如何获取每日重复的通知

时间:2018-04-19 18:30:14

标签: swift

当我调用我的通知功能时,它会在原始时间触发。但是,之后我再也没有收到通知。我注意到this post正在处理类似的问题。我改变了我的代码来模仿解决方案。我仍然没有收到另一个通知。

以下是代码:

<link rel="stylesheet" type="text/css" href="<?= base_url('css/style.css');?>">

目的是让它每天下午4点触发。

static func scheduleNotification(hour:Int, minutes:Int, completion: @escaping (Bool) -> ()) {
    let notificationContent = UNMutableNotificationContent()

    notificationContent.title = "Hello "
    notificationContent.subtitle = "Now might be a good time for a check in"

    var dateInfo = DateComponents()
    dateInfo.hour = hour
    dateInfo.minute = minutes

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
    print(trigger.nextTriggerDate()!)

    let request = UNNotificationRequest(identifier: Notifications.notificationIdentifier, content: notificationContent, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print("\(error)")
            completion(false)
        } else {
            completion(true)
        }
    })
}

我打印了nextTriggerDate函数的结果,看它是否会返回原始触发日期或第二天的日期。在这种情况下,日期是4-18-2018。

返回的触发器是

  

2018-04-18 23:00:00 +0000

我也不确定为什么返回的日期会增加7小时到我预期的触发时间。通知仍然在4:00开始。思考?

1 个答案:

答案 0 :(得分:0)

简短回答

添加

dateInfo.timeZone = TimeZone(abbreviation: "UTC")

它会像预期的那样工作。

<强>解释

我在第16小时和第0分钟尝试了自己。

我得到了14:00。原因是因为我住在德国和德国(格林尼治标准时间+2,夏令时)目前与UTC的距离为+2小时。

我的设备的默认时区是GMT + 2。我添加了16个小时,DateComponent将此日期作为GMT + 2处理,但将该值转换为UTC。 所以16(输入) - 2(GMT)= 14 UTC。

我总是尝试使用UTC日期...其他一切都让我头疼。