ios – Replace content material of delivered native notification SwiftUI


New to Xcode and Swift. My app has a timer that counts down. I might like for the countdown to be seen from the lock display as a notification, however I am unable to determine tips on how to (of if it is even doable to) replace the content material of an current native notification.

The one answer I’ve discovered thus far is to cancel the present notification and present a brand new one each second, which isn’t ultimate.

Code:

struct TimerApp: View {
    non-public let timer = Timer.publish(each: 1, on: .primary, in: .widespread).autoconnect() 
    @State non-public var isActive: Bool = true    // whether or not not timer is energetic 
    @State non-public var timeRemaining: Int = 600     // 60 seconds * 10 minutes = 10 min-countdown timer

    var physique: some View {
        // physique stuff
        // toggle isActive if consumer stops/begins timer

    }.onReceive(timer, carry out: { _ in 
        guard isActive else { return }

        if timeRemaining > 0 { 
            // want to replace present notification right here
            // *******

            // as a substitute, eradicating and including a brand new one proper now
            UNUserNotificationCenter.present().removeAllDeliveredNotifications()
            UNUserNotificationCenter.present().removeAllPendingNotificationRequests()
            addNotification()
 
            timeRemaining -= 1
        } else {
            isActive = false
            timeRemaining = 0
        }
    }

    func addNotification() {
        
        let heart = UNUserNotificationCenter.present()

        let addRequest = {
            let content material = UNMutableNotificationContent()
            content material.title = "App Title"
            content material.physique = "Time: (timeFormatted())"
            let set off = UNTimeIntervalNotificationTrigger(timeInterval: 0.0001, repeats: false)

            let request = UNNotificationRequest(identifier: "onlyNotification", content material: content material, set off: set off)
            heart.add(request)            
            
        }
        
        heart.getNotificationSettings { settings in
            if settings.authorizationStatus == .licensed {
                addRequest()
            } else {
                heart.requestAuthorization(choices: [.alert, .badge]) { success, error in
                    if success {
                        addRequest()
                    } else if let error = error {
                        print("error :( (error.localizedDescription)")
                    }
                }
            }
        }
    }

    func timeFormatted() -> String {
        // converts timeRemaining to 00:00 format and returns string
    }
}

And here’s what the hilariously dangerous answer seems to be like proper now.

enter image description here

Leave a Reply

Your email address will not be published.