如何创建一个通知,该通知将在 8 小时内每 8 次触发一次,12 次触发 12 次,以编程方式在 Swift iOS 中

How do I create a notification that will be triggered every 8 in 8 hours, 12 in 12, programmatically in Swift iOS

我正在创建一个应用程序来通知用户吃药。

我已经存储了您选择的时间段,例如 2 小时 2 小时、8 小时 8 小时等。 我正在转换为 double,然后在 addingTimeInterval 方法中乘以 3600,如下所示。

func notifications(name: String, timeToTime: String, firstTime: String) {
    let center = UNUserNotificationCenter.current()
    
    let content = UNMutableNotificationContent()
    content.title = "Chegou a hora de tomar \(name)"
    content.body = "Voce deve ingerir este remédio \(timeToTime)"
    content.sound = UNNotificationSound.default
    
    let timeInterval = handleToInt(time: timeToTime)
    let date = Date().addingTimeInterval(timeInterval * 3600)
    let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
    
    let request = UNNotificationRequest(identifier: "random", content: content, trigger: trigger)
    
    center.add(request)
}

这样我设置X小时后第一次闹钟,比如2小时后选择2,我转换成2,2小时后通知用户

timeToTime 变量是他选择的时间间隔。 handleToInt 方法转换为 int 或 double。

我在这里很迷茫...

下面是代码中出现的其他方法

private func handleTime(timeToTime: String) -> String {
    var timeToTime = timeToTime
    switch timeToTime {
    case "2 em 2 horas":
        timeToTime = "2"
    case "4 em 4 horas":
        timeToTime = "4"
    case "6 em 6 horas":
        timeToTime = "6"
    case "8 em 8 horas":
        timeToTime = "8"
    case "12 em 12 horas":
        timeToTime = "4"
    default:
        timeToTime = "8"
    }
    return timeToTime
}

func handleToInt(time: String) -> Double {
    let timeToInt = handleTime(timeToTime: time)
    let myInt = (timeToInt as NSString).integerValue
    
    return Double(myInt)
}

您可以使用UNTimeIntervalNotificationTrigger,例如:

// Fire every 2 hours (60 seconds × 60 minutes × 2 hours)
let hours = 2
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(hours) * 60 * 60, repeats: true)