swift - 每日本地通知工作了一天,然后停止了 [Swift]
问题描述
我为我的应用程序上的每日本地通知编写了一个代码,该代码将在每天下午 1:00(13:00)发送。我写它的那天,代码运行良好,并且通知在下午 1:00 准确发送。由于未知原因,它仅比现在效果好,但现在不起作用,我没有收到任何通知。
(我在应用程序的注册页面中编写了代码)
编码:
import UIKit
import FirebaseAuth
import Firebase
class SignUp: UIViewController {
@IBOutlet weak var emailSignupTF: UITextField!
@IBOutlet weak var passwordSignupTF: UITextField!
@IBOutlet weak var errorLabel: UILabel!
var message = ""
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.setHidesBackButton(true, animated: true)
//First Notification//
let content = UNMutableNotificationContent()
content.title = "תזכורת"
content.body = "לא לשכוח לעדכן את מיקומך בתדריך הקרוב"
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 13
dateComponents.minute = 0
// Create the trigger as a repeating event.
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents, repeats: true)
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}
解决方案
这里的问题是您通过说dateComponents.calendar = Calendar.current
然后设置小时和分钟值来专门获取今天的日期。这意味着通知将在每年的该日期在指定的小时和分钟发送。要解决此问题,只需执行以下操作:
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.hour = 13
dateComponents.minute = 0
现在通知将在每天 13:00 发送。参考:https ://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger
推荐阅读
- java - 为什么 leftMargin 将一半的数量添加到顶部和底部?
- php - 如何创建一个使用多行数据的表单?
- java - 如何在javafx中堆叠形状
- laravel - Laravel livewire - 检查复选框是否被选中
- html - 在 div 中添加容器不会将容器与中心对齐,以及如何在保持初始大小的同时获得滚动效果
- google-apps-script - 将代码从删除修改为清除内容 - Google Sheets Apps 脚本
- c# - 具有从嵌套集合中的项目动态创建的列的 DataGrid
- javascript - 如何根据第二个数组中的值将多个元素添加到数组 X 次?
- r - Purrr 将索引数据帧与数据帧相乘
- python - Python嵌套字典到熊猫df