I want my live activity to update the seconds, but if the app is closed, the live activity doesn't update anymore:
I have seen live activities update seconds before, but it doesn't work for me.
Here is my code for my SwiftUI Button:
Button(
action: {
if isActivityGoing == false {
let backgroundUIColor = UIColor(backgroundColor)
var backgroundR: CGFloat = 0
var backgroundG: CGFloat = 0
var backgroundB: CGFloat = 0
var backgroundAlpha: CGFloat = 0
backgroundUIColor.getRed(&backgroundR, green: &backgroundG, blue: &backgroundB, alpha: &backgroundAlpha)
let backgroundColorTable: [String: Double] = ["R": backgroundR, "G": backgroundG, "B": backgroundB]
let textUIColor = UIColor(textColor)
var textR: CGFloat = 0
var textG: CGFloat = 0
var textB: CGFloat = 0
var textAlpha: CGFloat = 0
textUIColor.getRed(&textR, green: &textG, blue: &textB, alpha: &textAlpha)
let textColorTable: [String: Double] = ["R": textR, "G": textG, "B": textG]
let activityAttributes = Seconds_Attributes(
backgroundColor: backgroundColorTable,
textColor: textColorTable
)
let timeSeconds: Int = Calendar.current.component(.second, from: Date())
let contentState = Seconds_Attributes.ContentState(seconds: timeSeconds)
let activityContent = ActivityContent(
state: contentState,
staleDate: Calendar.current.date(byAdding: .hour, value: 24, to: Date())!)
do {
activity = try Activity.request(
attributes: activityAttributes,
content: activityContent)
isActivityGoing = true
} catch (let error) {
print("Error occured: \(error.localizedDescription)")
isActivityGoing = false
}
Task(priority: TaskPriority.background) {
while isActivityGoing == true {
sleep(1)
let updatedContent = Seconds_Attributes.TimeSeconds(seconds: Calendar.current.component(.second, from: Date()))
let activityContent = ActivityContent(
state: updatedContent,
staleDate: Calendar.current.date(byAdding: .hour, value: 24, to: Date())!)
await activity?.update(activityContent)
}
}
} else {
let finalContent = ActivityContent(state: Seconds_Attributes.ContentState(seconds: 0), staleDate: nil)
Task {
await activity?.end(finalContent, dismissalPolicy: .immediate)
isActivityGoing = false
}
}
},
I have tried setting the priority to background for the task, but that doesn't seem to work.
I am expecting the live activity to update every time the second of the time changes.