我为我的应用编写了每日本地通知代码,该代码每天1:00 pm(13:00)发送。在我编写代码的那一天,代码运行良好,并且通知恰好在下午1:00发送。由于一个未知的原因,它只比以前好用,但现在不起作用,我没有收到任何通知。
((我在应用程序的Signup页面中编写了代码)
代码:
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