I will start to observe through activityEnablementUpdates
after app launched.
The handleLiveActivityStateChange
cannot be called when i turn on/off live activity settings.
Task {
for await enabled in ActivityAuthorizationInfo().activityEnablementUpdates {
self.handleLiveActivityStateChange(enabled)
}
}
Has anyone ever been in that situation ?
Am I using it wrong? What should I do?
Here are two things to consider when working with this asynchronous sequence. First and foremost, if the app is in the background, it likely doesn't get any CPU time, and the sequence won't emit any values. Second, there is an undocumented quirk about ActivityAuthorizationInfo. If we create multiple instances of this object, only one will be functional. It is probably a good idea to put it on the view itself. Or somewhere where you won't create it multiple times.
struct ContentView: View {
@State private var permissionTrackingTask: Task<Void, Never>?
@State private var currentActivity: Activity<ActivityEnablementWidgetsAttributes>?
// Create one instance and hold on to it.
private let activityAuthorizationInfo = ActivityAuthorizationInfo()
var body: some View {
List {
Button("Start Location Tracking & Live Activity") {
Task {
do {
let attributes = ActivityEnablementWidgetsAttributes(name: "Cute Emoji")
let state = ActivityEnablementWidgetsAttributes.ContentState(emoji: "😜")
let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil))
self.currentActivity = activity
} catch {
print("❌\(error)")
}
}
}
}
.onAppear {
print("👻areActivitiesEnabled: \(activityAuthorizationInfo.areActivitiesEnabled)")
self.permissionTrackingTask = Task {
for await update in activityAuthorizationInfo.activityEnablementUpdates {
print("🥳\(update)")
}
}
}
}
}
I have a small sample app demonstrating this case.