繁体   English   中英

iOS上的每日本地通知

[英]Daily local notification on iOS

我需要发出本地通知,每天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分钟发出警报。 此外,它也无法每天发出警报。 我做错了什么?

使用以下功能安排您的通知:

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM