- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
本地通知应该在 25-9-2021 发出。这是火灾时间的打印对象
▿ year: 2021 month: 9 day: 26 isLeapMonth: false
- year : 2021
- month : 9
- day : 25
- isLeapMonth : false
let content = UNMutableNotificationContent()
content.title = "Test title"
content.body = "sample test body"
var trigger:UNCalendarNotificationTrigger
let n = 1
let nextTriggerDate = Calendar.current.date(byAdding: .day, value: n, to: Date())!
let comps = Calendar.current.dateComponents([.year, .month, .day], from: nextTriggerDate)
trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
content.subtitle = "Sub title-Date-NonRepeat"
let request = UNNotificationRequest(identifier: "test.my.example", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { Error in
if let err = Error {
print("Notification Error:\(String(describing: err))")
}
}
我再次添加了日期与以下代码更改的时间
var comps = Calendar.current.dateComponents([.year, .month, .day], from: nextTriggerDate)
comps.day = 25
comps.hour = 12
comps.minute = 17
comps.second = 10
这是 comps 变量的 PO
var comps = Calendar.current.dateComponents([.year, .month, .day],from: nextTriggerDate)comps.day = 25comps.hour = 12comps.minute = 17comps.second = 10
最佳答案
您可能没有先请求许可
import SwiftUI
//struct and class should start with an uppercase
struct NotificationView: View {
//Central location for Notification code including the delegate
// A call to the notificationManager just like the one below has to be included in
// application(_:willFinishLaunchingWithOptions:) or
// application(_:didFinishLaunchingWithOptions:)
//https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate
//https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app
let notificationManager: NotificationManager = NotificationManager.shared
var body: some View {
VStack {
VStack {
Button("Request Permission") {
//Call a func here don't define it
notificationManager.requestAuthorization()
}
.frame(width: 200, height: 60, alignment: .center)
.foregroundColor(.black)
.background(Color.blue)
.cornerRadius(10.0)
.padding()
Button("Add custom trigger") {
let apiDate = DateComponents(year: 2021, month: 11, day: 10, hour: 16, minute: 0, second: 0)
notificationManager.scheduleBasedOnDaysBeforeDate(title: "test", body: "test", baseDate: Calendar.current.date(from: apiDate)!, xDaysBefore: 10, count: 12, identifier: UUID().uuidString)
}
.padding()
Button("Print Notifications") {
//Reusable method
self.notificationManager.printNotifications()
}
Button("Print Delivered Notifications") {
//Reusable method
self.notificationManager.printDeliveredNotifications()
}
.foregroundColor(.blue)
.padding()
Button("Delete Notifications") {
//Reusable method
self.notificationManager.deleteNotifications()
}
.foregroundColor(.blue)
.padding()
}
}
}
}
class NotificationManager: NSObject, UNUserNotificationCenterDelegate{
//Singleton is requierd because of delegate
static let shared: NotificationManager = NotificationManager()
let notificationCenter = UNUserNotificationCenter.current()
private override init(){
super.init()
//This assigns the delegate
notificationCenter.delegate = self
}
func scheduleUNCalendarNotificationTrigger(title: String, body: String, dateComponents: DateComponents, identifier: String, repeats: Bool = false){
print(#function)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: repeats)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if error != nil {
print(error!)
}
}
}
func scheduleUNTimeIntervalNotificationTrigger(title: String, body: String, timeInterval: TimeInterval, identifier: String, repeats: Bool = false){
print(#function)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: repeats)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if error != nil {
print(error!)
}
}
}
///Schedules `count` number of monthly notifications that occur `xDaysBefore` the `baseDate`
func scheduleBasedOnDaysBeforeDate(title: String, body: String, baseDate: Date, xDaysBefore: Int, count: Int, identifier: String){
print(#function)
var nextBaseDate: Date = baseDate
for n in 1...count{
guard let triggerDate: Date = Calendar.current.date(byAdding: .day, value: -xDaysBefore, to: nextBaseDate) else{
return
}
let components: DateComponents = Calendar.current.dateComponents([.month,.day, .hour,.minute,.second], from: triggerDate)
let id = identifier.appending(" \(n)")
scheduleUNCalendarNotificationTrigger(title: title, body: body, dateComponents: components, identifier: id)
//OR if you want specific seconds
//let interval = Calendar.current.dateComponents([.second], from: Date(), to: triggerDate).second ?? 1
//scheduleUNTimeIntervalNotificationTrigger(title: title, body: body, timeInterval: TimeInterval(interval), identifier: id)
let next = Calendar.current.date(byAdding: .month, value: 1, to: nextBaseDate)
if next != nil{
nextBaseDate = next!
}else{
print("next == nil")
return
}
}
self.printNotifications()
}
func requestAuthorization() {
print(#function)
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Access Granted!")
} else {
print("Access Not Granted")
}
}
}
func deleteNotifications(){
print(#function)
notificationCenter.removeAllPendingNotificationRequests()
}
///Prints to console schduled notifications
func printNotifications(){
print(#function)
notificationCenter.getPendingNotificationRequests { request in
print("UNTimeIntervalNotificationTrigger Pending Notification")
for req in request{
if req.trigger is UNTimeIntervalNotificationTrigger{
print((req.trigger as! UNTimeIntervalNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
}
}
print("UNCalendarNotificationTrigger Pending Notification")
for req in request{
if req.trigger is UNCalendarNotificationTrigger{
print((req.trigger as! UNCalendarNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
}
}
}
}
///Prints to console delivered notifications
func printDeliveredNotifications(){
print(#function)
notificationCenter.getDeliveredNotifications { request in
for req in request{
print(req)
}
}
}
//MARK: UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.banner)
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
NotificationView()
}
}
运行此代码。首先单击“请求权限”,然后单击“添加自定义触发器”,当您单击“打印”时,您应该会在控制台中看到您的通知
关于ios - 为什么本地通知没有为 UNCalendarNotificationTrigger 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69310525/
好的 - 我现在对这段代码感到非常沮丧,准备放弃!基本上,当模拟到模拟器或实际设备时,我得到 requestAuthorisation 可以正常工作,但触发器不会启动。我在网上关注了几个人,他们的代码
我正在使用以下方法来每小时触发一次本地通知。 let reminderTrigger = UNCalendarNotificationTrigger.init(dateMatching: NSCale
先生们早上好 我知道这样使用 UNCalendarNotificationTrigger: var dateComponents = DateComponents() dateComponents.h
我想开发一个提醒应用程序,当我们设置提醒时需要发送本地通知。我开发了一些代码,即使我设置了多个通知,也只触发一个通知。如果我在晚上 7:30、晚上 7:31、晚上 7:32 设置提醒,则通知仅在晚上
在an earlier question我提到了安排本地通知的问题。问题的真正原因是我曾经使用以下代码来创建触发器,但它不起作用: let calendar = ... let notificatio
本地通知应该在 25-9-2021 发出。这是火灾时间的打印对象 ▿ year: 2021 month: 9 day: 26 isLeapMonth: false year : 2021 month
我的应用程序必须每隔 n 天提醒用户一些事情。 目前,我有 var dateComponents = DateComponents() dateComponents.hour = userHour d
我注意到,如果我创建一个带有自定义日期的 UNCalendarNotificationTrigger,它不会被添加,除非我输入:让 trigger = UNCalendarNotificationTr
我是一名优秀的程序员,十分优秀!