gpt4 book ai didi

ios - 带有 fireDate 的通知会立即触发

转载 作者:行者123 更新时间:2023-11-30 12:40:08 24 4
gpt4 key购买 nike

我收到以下通知,该通知设置为在当天晚上 9 点(如果当前在晚上 9 点之前)或第二天晚上 9 点(如果已经超过晚上 9 点)触发。

一切看起来都不错,但无论当前时间如何,它总是立即显示通知。

let hour = 21
let minute = 0

let calendar = NSCalendar(identifier: .gregorian)!;

var dateFire = Date()

// if today's date is passed, use tomorrow
var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire)

if (fireComponents.hour! > hour
|| (fireComponents.hour == hour && fireComponents.minute! >= minute) ) {

dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date
fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire);
}

// set up the time
fireComponents.hour = hour
fireComponents.minute = minute

// schedule local notification
dateFire = calendar.date(from: fireComponents)!

print(dateFire)

let notification = UILocalNotification()
notification.alertBody = "TEST"
notification.soundName = "Default"
notification.fireDate = dateFire

UIApplication.shared.presentLocalNotificationNow(notification)

最佳答案

您正在调用 UIApplication.shared.presentLocalNotificationNow,它的作用正如其所言,它会在调用该方法时立即显示通知。

如果您想安排本地通知,您需要首先导入UserNotifications(iOS 10+)

import UserNotifications

然后您可以像这样安排通知:

func registerLocalNotification(date: Date) {
let content = UNMutableNotificationContent()

content.categoryIdentifier = "YOUR_IDENTIFIER"
content.title = "YOUR_TITLE"
content.body = "NOTIFICATION_BODY"
content.sound = UNNotificationSound.default()

// Use date components to create a trigger time
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: date)
print("Register: \(triggerDate)")
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
// Instantiate the notification request
let request = UNNotificationRequest(identifier: "SOME_IDENTIFIER", content: content, trigger: trigger)

// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
// Handle error if necessary
print("Notification Added")
}

}

您还需要确保您已在 AppDelegate 中使用新的 UserNotifications 正确注册通知

import UserNotifications

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

if granted {
UIApplication.shared.registerForRemoteNotifications()
}

}

return true
}

关于ios - 带有 fireDate 的通知会立即触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com