在特定时间段后停止本地通知

Stop local notification after specific time period

我在应用程序中使用本地通知。我每隔 1 小时、2 小时等触发本地通知。我想在 8 小时后停止此通知。我用来触发本地通知的代码如下:-

func localNotificationFire(timeInterval: Int) {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
        if error != nil {
            print("Request authorization failed!")
        } else {
            print("Request authorization succeeded!")
            
           let content = UNMutableNotificationContent() // Содержимое уведомления
            
            content.title = ""
            content.body = kNotificationReminder
            content.sound = UNNotificationSound.default
            content.badge = 1
            
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timeInterval), repeats: true)
            let request = UNNotificationRequest(identifier: "notification.id.01", content: content, trigger: trigger)
            // 4
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
    } 
}

我知道,我可以像UNUserNotificationCenter.current().removeAllPendingNotificationRequests()一样停止这个通知 但是我想自动停止这个通知。

所以根据@Paulw11 和@TiranU 的回答,我安排了所需数量的个人通知。解决方法如下:-

func localNotificationFire(timeInterval: Int, totalHours: Int) {
    let num = totalHours/timeInterval
    for i in 0..<num {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
            if error != nil {
                print("Request authorization failed!")
            } else {
                print("Request authorization succeeded!")
                
                let content = UNMutableNotificationContent() 
                
                content.title = ""
                content.body = kNotificationReminder
                content.sound = UNNotificationSound.default
                content.badge = 1
                
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval((i+1)*timeInterval), repeats: false)
                let request = UNNotificationRequest(identifier: "notification.id.\(i)", content: content, trigger: trigger)
                // 4
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            }
        }
    }
}

其中 total hours 是我想要触发通知的时间,timeInterval 是触发通知的时间间隔。