I'm working on an iOS app that shows a sheet when a user taps on a notification. The issue arises when the app is brought from the background to the foreground upon tapping a notification. Despite setting a @Published property showReminderDetail to true to present a sheet with more information, it gets overridden and resets to false due to the initialization logic in my @main class, negating the state change.
Here's the sequence of events as logged by my console:
Current state of showReminderDetail: false Notification received
Handling notification for reminder ID: E6BDC19C-17F0-4945-96AE-772A4DAA36B9
Notification received for reminder with ID: E6F0-4945-96AE-772A4DAA36B9
selectedReminderID is now: Optional(E6BDC19C-17F0-4945-96AE-772A4DAA36B9)
showReminderDetail set to: true
Current state of showReminderDetail: false
Here is a simplified version of my relevant app logic:
class AppLogic: NSObject, ObservableObject {
@Published var showReminderDetail = false
@Published var selectedReminderID: UUID? = nil
// Other properties and initializers
func handleNotificationResponse(with reminderID: UUID) {
DispatchQueue.main.async {
self.selectedReminderID = reminderID
self.showReminderDetail = true
}
}
// Additional methods
}
extension AppLogic: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Notification handling logic
}
}
and my content view:
struct ContentView: View {
@EnvironmentObject var appLogic: AppLogic
var body: some View {
// ContentView structure
.sheet(isPresented: $appLogic.showReminderDetail) {
// Sheet content
}
}
}
and my @main:
@main
struct Conditional_Reminder_AppApp: App {
let persistenceController = PersistenceController.shared
// Initialize AppLogic with the ReminderStorage instance
@StateObject var appLogic: AppLogic
init() {
let reminderStorage = ReminderStorage(context: persistenceController.container.viewContext)
_appLogic = StateObject(wrappedValue: AppLogic(reminderStorage: reminderStorage))
}
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.environmentObject(appLogic)
}
}
}
I think the problem is how my @main class initializes the AppLogic object or possibly with how state restoration is handled when the app transitions from background to foreground. However, I've no clue.
How can I maintain the showReminderDetail state as true when the app is brought to the foreground, allowing the sheet to be presented as intended?
I tried handling state as UserDefaults instead of an observable object, but that didn't work either. I'm expecting "Current state of showReminderDetail: true" after tapping a notification and seeing a sheet.