Search code examples
xamarinxamarin.formsxamarin.iosuilocalnotificationlocalnotification

How to navigate to a particular page when user taps on a Local Notification in Xamarin Forms app?


Hi am developing a Xamarin Forms app. i have implemented local notifications in the app. When the notification has fired, upon clicking the notification it has to navigate to a particular page. In iOS project in Appdelegate.cs i wrote this method

    public async  override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)

which will fire when the user taps on the notification. here i need to navigate to a page. Here i wrote the below line of code

            App.Current.MainPage  = new NavigationPage(new FavoritesPage());

It is navigating to the Favorites page but it is just displaying a blank page. OnNavigatedTo method is not calling for the FavoritesViewModel and in the Onnavigated to am calling a method which takes id(this id comes from the notification) as parameter to get a particular favorite Here two questions 1) How to navigate to a Specific page 2) How to pass a parameter along with the page navigation. Can someone please help me to solve this issue.


Solution

  • For 1:

    You want to push to a new Page, but what you did is replacing the app's MainPage. please try PushAsync. You can subscribe a MessagingCenter in App:

    public App ()
    {
        InitializeComponent();
    
        MainPage = new NavigationPage(new MainPage());
    
        MessagingCenter.Subscribe<object, string>(this, "Push", async (sender, favoriteID) =>
        {
            var favorite = new FavoritesPage();
            favorite.FavoriteID = favoriteID;
            await (MainPage as NavigationPage).PushAsync(favorite, true);
        });
    }
    

    This Lambda will fire when you call MessagingCenter.Send<object, string>(this, "Push", "01"); The string 01 here is the ID what I want to push.

    For 2:

    Before I push to a new page, I define a property called FavoriteID in this page, then I pass the string using method above.