0

我需要制作一个本地通知,每天在 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 分钟发出警报。此外,它也不能每天报警。我做错了什么?

4

1 回答 1

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)
}
于 2017-07-11T13:14:35.090 回答