【问题标题】:DateComponents and Notifications Not Showing日期组件和通知未显示
【发布时间】:2018-01-05 02:18:12
【问题描述】:

我制作了一个待办事项列表应用程序。在应用程序中,用户可以选择 4 个按钮中的 1 个来设置通知。即刻、上午、下午和晚上。目前,晚上和直接工作,但上午和下午不工作,我不确定为什么。

这是我晚上的代码:

@IBAction func eveningTapped(_ sender: Any) {

    eveningEnabled = true
    morningEnabled = false
    lockscreenEnabled = false
    afternoonEnabled = false
}

if eveningEnabled == true {
        var dateComponents = DateComponents()
        dateComponents.hour = 18
        dateComponents.minute = 00
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
        let content = UNMutableNotificationContent()
        content.title = taskTextField.text!
        content.body = DescTextField.text!
        content.sound = UNNotificationSound.default()
        content.badge = 1

        let identifier = "UYLLocalNotification"
        let request = UNNotificationRequest(identifier: identifier,
                                            content: content, trigger: trigger)
        center.add(request, withCompletionHandler: { (error) in
            if error != nil {
                // Something went wrong - another alert
            }
        })
    }

这工作完全正常,但早上不起作用,这里是代码:

@IBAction func morningTapped(_ sender: Any) {

    morningEnabled = true
    lockscreenEnabled = false
    afternoonEnabled = false
    eveningEnabled = false
}

if morningEnabled == true {
        var dateComponents = DateComponents()
        dateComponents.hour = 07
        dateComponents.minute = 00
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
        let content = UNMutableNotificationContent()
        content.title = taskTextField.text!
        content.body = DescTextField.text!
        content.sound = UNNotificationSound.default()
        content.badge = 1

        let identifier = "UYLLocalNotification"
        let request = UNNotificationRequest(identifier: identifier,
                                            content: content, trigger: trigger)
        center.add(request, withCompletionHandler: { (error) in
            if error != nil {
                // Something went wrong - another alert
            }
        })
    }

【问题讨论】:

  • 这是你的真实代码吗? {} 不匹配。

标签: swift push-notification nsdatecomponents


【解决方案1】:

由于您的代码在两个操作中完全相同(DateComponents 除外),因此运行时应该没有区别。

但是由于您有所不同(“早上”不起作用),原因必须在其他地方(而不是在您在此处发布的代码中)。可能你早上的 tapAction 没有在 InterfaceBuilder 中正确连接?

如果您发布更多代码,我们可能会更好地帮助您找到错误。

首先,您应该检查当您点击时是否正在执行您的 tapAction。您可以通过添加日志命令来做到这一点,如下所示:

print("Morning was tapped")

并将此代码放入您的 tapAction 中。然后你应该在你的日志控制台上得到这个日志,点击相应的按钮。

【讨论】:

  • 好的,所以我检查了我的连接以及按钮何时正常工作并且所有连接都正确。我将再次测试通知,因为我的项目最近一直在播放。会及时更新
  • 现在一切正常。由于某种原因,连接有点奇怪。感谢您的帮助
  • 所以,如果您将我的答案标记为正确答案,那就太好了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多