Ios 特定时间段的本地通知取消

Ios 特定时间段的本地通知取消,ios,swift,local,uilocalnotification,Ios,Swift,Local,Uilocalnotification,我想在某个特定时间发出本地通知,就像水通知一样。 和用户一样,用户可以设置每2小时的起床时间和上床时间n饮水通知,那么我如何设置从上床到起床时间之间的时间,我的本地通知获胜;t火灾,但通知将每2小时火灾一次 请帮帮我。 谢谢您所能做的就是获得唤醒时间和睡眠时间之间的时间,以及您希望发出通知的频率 首先,您需要创建一个本地通知,该通知每天在特定时间重复 func createNotification(title: String, body: String, hour: Int, repeats:

我想在某个特定时间发出本地通知,就像水通知一样。 和用户一样,用户可以设置每2小时的起床时间和上床时间n饮水通知,那么我如何设置从上床到起床时间之间的时间,我的本地通知获胜;t火灾,但通知将每2小时火灾一次

请帮帮我。
谢谢

您所能做的就是获得唤醒时间和睡眠时间之间的时间,以及您希望发出通知的频率

首先,您需要创建一个本地通知,该通知每天在特定时间重复

func createNotification(title: String, body: String, hour: Int, repeats: Bool, identifier: String) {
    
    //calendar
    let calendar = Calendar.current
   
    let content = UNMutableNotificationContent()
   
    content.title = title
    content.body = body

    let today = Date()
    
    let futureDate = calendar.date(byAdding: .hour, value: hour, to: today)
    
    let hourComponent = calendar.dateComponents([.hour], from: futureDate!)
    
    let trigger = UNCalendarNotificationTrigger(dateMatching: hourComponent, repeats: repeats)
    
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    
    center.add(request, withCompletionHandler: {(error) in })
}
其次,将此代码放在viewDidLoad()中或您希望设置通知的位置。我在这里所做的是获得唤醒时间和睡眠时间,然后通过将小时数除以频率,找到必须使用我想要的频率发出的通知数

最后,我创建了一个for循环,该循环根据我添加到唤醒时间的时间创建通知。例如,第一次火灾通知发生在早上6点+1x2=8点,第二次火灾通知发生在早上6点+2x2=10点

    //calendar
    let calendar = Calendar.current
    
    //set the wakeup and sleep hour
    let wakeupHour = 6 //6am
    let sleepHour = 18 // 6pm
    
    //Obtain starting time using date components
    let wakeup = DateComponents(calendar: calendar, hour: wakeupHour)
    
    //Obtain ending time using date components
    let sleep = DateComponents(calendar: calendar, hour: sleepHour)
    
    //calculate the number of hours between the two time
    
    //obtain number of hour difference
    let hourDifference = calendar.dateComponents([.hour], from: wakeup, to: sleep)
    
    //how many hours do you want
    let frequency:Int = 2
    
    //how many notifications will there be between the wakeup and sleeptime
    let numberOfNotifications:Int = hourDifference.hour! / frequency
    
    //create the notifications
    for num in 1...numberOfNotifications {
        //hour that each notification will fire off
        let hour = wakeupHour + frequency * num
           createNotification(title: "Drink Up", body: "Drink Up", hour:  hour, repeats: true, identifier: "drink\(hour)")
    }

我仍在学习swift,因此这可能不是解决此问题的最有效方法,但我希望这能有所帮助

不能按频率设置通知。你必须给出具体的时间。比如在9、11、1、3、5等位置显示通知,这样您就可以完全控制何时开始和结束。此外,请注意,每个设备(所有应用程序)可以有多少本地推送通知是有限制的。因此,不要在几天内添加/创建通知。每次用户打开你的应用时。您可以重新创建下一个“x”通知。