In Swift, when clicking on a local notification, how to open the detail view of the linked object?

66 Views Asked by At

In my application, there is a list of items and each one is linked to its detail view. Under given circumstances, I get notifications related to objects. In the 'userInfo' field of the notification, I've set up the linked object's UUID. In the application, I check whether the function 'userNotificationCenter(_:didReceive:withCompletionHandler:)' has been fired (using a 'if let') and, in this case, I display the detail screen of the linked object.

var body: some View {
    if let objID = locationManager.notificationManager.nofifiedObjID, strlen(objID.uuidString) > 0 {
        ObjDetailView(obj: objsList.getObj(_id: objID))
    } else {
        NavigationStack {
            List {
                ForEach (objsList.objs) { obj in
                    NavigationLink {
                        ObjDetailView(obj: obj)
                    } label: {
                        ObjListItem(obj: obj)
                    }
                }
            }
            .navigationTitle(String(localized: "__objs"))
        }
    }
}

My problem is that, if the user clicks on the notification, which would lead to the corresponding detail screen being displayed, there is no 'back' button, what stucks the application on this screen.

I've tried to set the 'ObjDetailView' in a NavigationLink, but it doesn't work. Another way could be to build the normal List of NavigationLinks and then to 'fire' the one related with the local notification's 'userInfo', but I couldn't find a way.

Do you have any advise about how to let a notification lead to the detail view of the linked object and let the application be used normally afterwards?

1

There are 1 best solutions below

1
Stoic On

If you want the back button to work correctly, you need ObjDetailView to be in a NavigationStack.

Instead of

if let ... {
    ObjDetailView(obj: objsList.getObj(_id: objID))
} else {
    NavigationStack {
        List {
            ...
        }
    }
}

you should have

NavigationStack {
    if let ... {
        ObjDetailView(obj: objsList.getObj(_id: objID))
    } else {
        List {
            ...
        }
    }
}