Home > Mobile >  How do I create a notification that will be triggered every 8 in 8 hours, 12 in 12, programmatically
How do I create a notification that will be triggered every 8 in 8 hours, 12 in 12, programmatically

Time:02-12

I'm creating an app to notify the user to take his Medicine.

I'm already storing your selection of periods, like, 2 in 2 hours, 8 in 8, etc. I'm converting to a double and then multiplying by 3600 in the addingTimeInterval method, as shown below.

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)
}

That way, I set the first alarm for X hours from now, for example, selecting 2 in 2 hours, I convert it to 2, and the user will be notified in 2 hours

The timeToTime variable is his choice of interval. The method handleToInt converts to an int or a double.

I'm very lost here...

Here are the other methods that appear in the code

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)
}

CodePudding user response:

You can use UNTimeIntervalNotificationTrigger, e.g.:

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