Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

swift - SwiftUI - Schedule a notification to repeat after an specific date

I'm a SwiftUI beginner. I'm creating an app and in the add view, the user can pick a date to start the notifications and in a picker list choose how often it repeats, like 15 min, 1 hour, 2 hours, etc. I did create the part that it schedule the first notification, but I don't know how to create another notification that repeats after this first one happens.

Here's my code

private func scheduleNotification(medication: Medication) {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound])  {
            success, error in
                if success {
                    print("authorization granted")
                } else if let error = error {
                    print(error.localizedDescription)
                }
    }
    let content = UNMutableNotificationContent()
        content.title = "Lembrete"
    content.body = "Tomar (medication.name ?? "Medicamento")"
        content.sound = UNNotificationSound.default
    
    guard let timeInterval = medication.date?.timeIntervalSinceNow else {return}
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
    
    let request = UNNotificationRequest(identifier: medication.id!, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request)
}
}

Thanks,

question from:https://stackoverflow.com/questions/65907666/swiftui-schedule-a-notification-to-repeat-after-an-specific-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

when the notifications should send every "timeInterval" you just have to set the parameter repeats in trigger to true.

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

EDIT: I also found an article: https://www.hackingwithswift.com/read/21/2/scheduling-notifications-unusernotificationcenter-and-unnotificationrequest


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...