Open my app from local notification

TripleDoubleTripleDouble BGMember ✭✭✭
edited October 25 in Xamarin.iOS

1 How to open my app when I press a local notification ?
2 How to dismiss the notification? In android I just swipe it to left.

My notification code

partial void SetnNotification(UIButton sender)
    {
        RegisterForNotifications();
        ScheduleNotification();
    }

void RegisterForNotifications()
    {
        // Create action
        var actionID = "check";
        var title = "Check";
        var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.Foreground);

        // Create category
        categoryID = "notification";
        var actions = new UNNotificationAction[] { action };
        var intentIDs = new string[] { };
        //var categoryOptions = new UNNotificationCategoryOptions[] { };
        var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);

        // Register category
        var categories = new UNNotificationCategory[] { category };
        UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));

        UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert
                                                              | UNAuthorizationOptions.Badge
                                                              | UNAuthorizationOptions.Sound,
                                                              (a, err) => {
                                                                  //TODO handle error
                                                              });
    }

    void ScheduleNotification()
    {
        // Create content
        var content = new UNMutableNotificationContent();
        content.Title = "Title";
        content.Subtitle = "Subtitle";
        content.Body = "Body";
        content.Badge = 1;
        content.CategoryIdentifier = categoryID;
        content.Sound = UNNotificationSound.Default;


        var notification = new UILocalNotification();
        // Fire trigger in one seconds
        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);

        var requestID = "notificationRequest";   ///sampleRequest
        var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

        //Here I set the Delegate to handle the user tapping on notification
        UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => 
        {
            if (err != null)
            {
                // Report error
                System.Console.WriteLine("Error: {0}", err);
            }
            else
            {
                // Report Success
                System.Console.WriteLine("Notification Scheduled: {0}", request);
            }
        });
    }


public  class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{

    public UserNotificationCenterDelegate()
    {

    }

    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, [BlockProxy(typeof(AdAction))] Action completionHandler)
    {
        // Handle notification tap here


        // Take action based on Action ID
        switch (response.ActionIdentifier)
        {
            case "reply":
                // Do something
                break;
            default:
                // Take action based on identifier
                if (response.IsDefaultAction)
                {
                    // Handle default action...

                    //var mainActivitiy = this.Storyboard.InstantiateViewController("ViewController");
                    //this.NavigationController.PushViewController(mainActivitiy, true);
                }
                else if (response.IsDismissAction)
                {
                    // Handle dismiss action
                    //var requests = new string[] { "notificationRequest" };
                    //UNUserNotificationCenter.Current.RemoveDeliveredNotifications(requests);
                }
                break;
        }

        completionHandler();
    }


    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {

        completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Badge);
    }

}
}

Answers

  • TripleDoubleTripleDouble BGMember ✭✭✭

    Any ideas?

    I am trying to that

    var mainActivitiy = this.Storyboard.InstantiateViewController("ViewController");
    this.NavigationController.PushViewController(mainActivitiy, true);

    in DidReceiveNotificationResponse() method in UserNotificationCenterDelegate class,
    but I get null reference for Storyboard and NavigationController.

    Because of that when I press button for sent notification I am trying to do that :

    UserNotificationCenterDelegate userNotificationDelegate =
    new UserNotificationCenterDelegate(this.Storyboard, this.NavigationController);

            userNotificationDelegate.mStoryboard = this.Storyboard;
            userNotificationDelegate.mNavigationController = this.NavigationController;
    
            List<UserNotificationCenterDelegate> list = new List<UserNotificationCenterDelegate>();
    
            list.Add(userNotificationDelegate);
    
            var userNotificationDelegateAsJSON = JsonConvert.SerializeObject(list);
            File.WriteAllText(mNotificationFileName, userNotificationDelegateAsJSON);
    

    In general I added two properties in UserNotificationCenterDelegate class

    public UIStoryboard mStoryboard;
    public UINavigationController mNavigationController.

    When I tap notification in DidReceiveNotificationResponse() method in UserNotificationCenterDelegate class,
    I am trying to read the saved file, but get this error

    string userNotificationDelegateAsJSON = File.ReadAllText(mNotificationFileName);

            try
            {
                if (userNotificationDelegateAsJSON == null || userNotificationDelegateAsJSON == string.Empty)
                {
                    mNotificationList = new List<UserNotificationCenterDelegate>();
                }
                else
                {
                    mNotificationList = JsonConvert.DeserializeObject<List<UserNotificationCenterDelegate>>(userNotificationDelegateAsJSON);
    
                    mNotification = mNotificationList[0];
                }
    
                if (mNotificationList == null)
                {
                    mNotificationList = new List<UserNotificationCenterDelegate>();
                }
            }
            catch (Exception e)
            {
                if (userNotificationDelegateAsJSON == null)
                {
                    mNotificationList = new List<UserNotificationCenterDelegate>();
                }
                else
                {
                    mNotificationList = JsonConvert.DeserializeObject<List<UserNotificationCenterDelegate> >(userNotificationDelegateAsJSON);
    
                    mNotification = mNotificationList[0];
                }
    
                if (mNotificationList == null)
                {
                    mNotificationList = new List<UserNotificationCenterDelegate>();
                }
            }
    
    
    
            mStoryboard = mNotification.mStoryboard;
    
            mNavigationController = mNotification.mNavigationController;
    

  • TedRogersTedRogers USMember ✭✭✭✭

    @TripleDouble Can you provide a sample project?

  • TripleDoubleTripleDouble BGMember ✭✭✭

    @TedRogers
    Here is my project

Sign In or Register to comment.