gpt4 book ai didi

ios - 如何每天每天重复几个小时的本地通知?

转载 作者:行者123 更新时间:2023-12-01 19:33:47 25 4
gpt4 key购买 nike

我在google上进行了研究,并为我的应用创建了本地通知(“洗手提醒”),但我认为我在此上犯了一个错误,因为我将其设置为每天08:00 AM-10:00 PM之间,但它在9点发送了第一条通知: 00 AM,但不会在10:00重复。

UI屏幕截图将帮助您了解我想做什么。

enter image description here

功能:

 func createNotify(){
let now = Date().shortTime
if now < endTime.shortTime{

let content = UNMutableNotificationContent()
content.title = titles.randomElement()!
content.body = contents.randomElement()!
content.sound = UNNotificationSound.default

let interval:TimeInterval = 3600.0 // 1 minute = 60 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)
let request = UNNotificationRequest(identifier:"washHands", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request)
}else{
print("do nothing")
}
}

AppDelegate.swift:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

center.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
self.center.requestAuthorization(options: self.options) { (accepted, error) in
if !accepted {
print("Error")
}
}
}
}

center.delegate = self

BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.labters.korona-evdekal.washHands",
using: DispatchQueue.global()
) { task in
self.scheduleLocalNotification()
}

FirebaseApp.configure()
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

return true
}


func scheduleLocalNotification() {
let request = BGProcessingTaskRequest(identifier: "com.labters.korona-evdekal.washHands")
request.requiresNetworkConnectivity = false
request.requiresExternalPower = false
request.earliestBeginDate = Date(timeIntervalSinceNow: 3600.0)
do {
try BGTaskScheduler.shared.submit(request)
HealthView().createNotify()
} catch {
print("Could not schedule notification: (error)")
}
}

func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
-> Void) {
completionHandler([.alert, .badge, .sound])
}

最佳答案

let interval:TimeInterval = 60.0 // 1 minute = 60 seconds

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)

使用 UNTimeIntervalNotificationTrigger而不是 UNCalendarNotificationTrigger,因为要在指定的日期和时间安排本地通知的传递时使用 UNCalendarNotificationTrigger对象,而要在经过指定的秒数后安排本地通知的传递时使用 UNTimeIntervalNotificationTrigger对象。

https://developer.apple.com/documentation/usernotifications/untimeintervalnotificationtrigger

关于ios - 如何每天每天重复几个小时的本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60969580/

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