iOS上的每日本地通知

时间:2017-07-11 12:42:06

标签: ios unnotificationrequest unnotificationtrigger

我需要制作本地通知,每天19:30提醒用户。

这就是我所做的:

var dateComponents = DateComponents()
    dateComponents.hour = 19
    dateComponents.minute = 30
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)    

    let identifier = "daily.alarm"
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
      if error != nil {
        debugPrint("center.add(request, withCompletionHandler: { (error)")
      } 
    })

但是,我发现通知在19:30没有提醒。相反,它提前15分钟发出警报。此外,它也不能每天报警。我做错了什么?

1 个答案:

答案 0 :(得分:0)

使用以下功能安排通知:

func registerLocal() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Yas!")
        } else {
            print("Ohhh No!!")
        }
    }
}

func scheduleLocal() {
    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Drink Milk"
    content.body = "Two Servings A Day Keeps Bone Problems At Bay."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "whater"]
    content.sound = UNNotificationSound.default()

    var dateComponents = DateComponents()
    dateComponents.hour = 19
    dateComponents.minute = 30

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}