我做了一个待办事项列表应用程序。在应用程序中,用户可以选择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
}
})
}
答案 0 :(得分:1)
由于两个操作中的代码完全相同(除了DateComponents),因此运行时应该没有区别。
但是因为你有区别('早上'不工作),原因必须是其他地方(而不是代码,你在这里发布)。也许你的tapAction for morning在InterfaceBuilder中没有正确连接?
如果您要发布更多代码,我们可以更好地帮助找到错误。
首先你应该检查,当你点击时,你的tapAction正在执行。您可以通过添加日志命令来执行此操作,如下所示:
print("Morning was tapped")
并将此代码放入tapAction。然后,在点击相应的按钮后,您应该在日志控制台上获取此日志。