特定日期和时间的本地通知不起作用。迅速

Posted

技术标签:

【中文标题】特定日期和时间的本地通知不起作用。迅速【英文标题】:Local Notification for specific date and time is not working. Swift 【发布时间】:2018-10-20 10:36:47 【问题描述】:

我试图在单击按钮时在特定日期和时间触发本地通知,但它不起作用。下面是代码:

@IBAction func setReminderBtnPressed (_ sender: UIButton) 
    var dateString = String()
    dateString = "2018-10-20 18:11:00"
    //let date = Date(timeIntervalSinceNow: 60) //Working Fine
    let date = globalMethods.convertStringToDate(dateStr: dateString) //log 2018-10-20 10:11:00 +0000 
    let content = UNMutableNotificationContent()
    content.title = "Don't forget"
    content.body = "Buy some milk"
    content.sound = UNNotificationSound.default()
    let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) //log ▿ year: 2018 month: 10 day: 20 hour: 18 minute: 11 second: 0 isLeapMonth: false
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler:  (error) in
        if let error = error 
            // Something went wrong
            print(error)
        
    )


func convertStringToDate(dateStr: String) -> Date 
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current// (abbreviation: "GMT+0:00")
    let dateFromString = dateFormatter.date(from: dateStr)
    print("dateFromString: ", dateFromString!)
    return dateFromString!

提前致谢。

【问题讨论】:

没有错误信息,可以查看注释中代码旁边写的日志。 是的,我可以看到,但是当我打印 triggerDate 的日志时,它会正确显示。您可以查看打印到下一个代码的日志。 编辑了代码。请检查。 【参考方案1】:

确保您已授权该应用向用户发送通知。

在你的AppDelegateapplication(_:didFinishLaunchingWithOptions:),请求授权:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound])  (success, error) in
    if let error = error 
        debugPrint("Error: \(error)")
    

UNUserNotificationCenter.current().delegate = self

并且,在你的AppDelegate中确认UNUserNotificationCenterDelegate,并实现方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 

    completionHandler(.alert)

【讨论】:

以上是关于特定日期和时间的本地通知不起作用。迅速的主要内容,如果未能解决你的问题,请参考以下文章

在特定时间和日期调用 iOS 应用程序

每周特定日期的本地通知

Flutter:预定的通知日期时间

为日期数组设置警报通知

如果当前日期时间超过预定日期时间,如何删除本地通知?

如何阻止计划的本地通知在特定日期后触发?