0

I am using Xamarin.forms and implemented Local push notification for iOS. It is working successfully when I am debugging the app through visual studio even when the app is minimized, the app can able to receive the notification. But while running the app directly without debugging through visual studio, the app is not able to display the notification. Kindly guide me on this.

Then I also tried by releasing the app to the app store but experienced the same, the app is not able to receive the notification it not even in foreground mode.

I already have selected the "Background fetch" property under Background Modes in Info.plist. I have also added below the line in my FinishedLaunching method

UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);

Entire Implementation of code is as below

   public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        try
        {
            UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);

            try
            {                    

                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert |
                        UNAuthorizationOptions.Sound |
                        UNAuthorizationOptions.Sound,
                        (granted, error) =>
                        {
                            if (granted)
                            {
                                InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);                                    
                            }
                        });
                }
                else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());

                    UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                }
                else
                {
                    UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                    UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                }

                bool IsRegistered = UIApplication.SharedApplication.IsRegisteredForRemoteNotifications;
            }
            catch (Exception ex)
            {
                UIAlertView avAlert = new UIAlertView("FinishedLaunching Push Notification Exception", ex.Message, null, "OK", null);
                avAlert.Show();
            }

            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

            LoadApplication(new MessengerClient.App());

        }
        catch (Exception ex)
        {
            NativeHelper.SendUnhandledException(ex, NativeHelper.iOS + ": FinishedLaunching");
        }
        return base.FinishedLaunching(app, options);
    }

    public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
    {  
        /// reset our badge
        UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;

        /// Cancel/clear all Local notifications fronm the tray.
        UIApplication.SharedApplication.CancelLocalNotification(notification);

        /// Cancel/clear all notifications fronm the tray.
        UIApplication.SharedApplication.CancelAllLocalNotifications();
    }

code for displaying the notification is as below.

UILocalNotification notification = new UILocalNotification();
        notification.FireDate = NSDate.FromTimeIntervalSinceNow(1);
        notification.AlertAction = title;
        notification.AlertBody = content;
        notification.AlertTitle = title;
        notification.SoundName = UILocalNotification.DefaultSoundName;
        notification.ApplicationIconBadgeNumber = 1;            
        UIApplication.SharedApplication.ScheduleLocalNotification(notification);

I know this is the repeat question but, I tried all the workaround but didn't work for me.

James Z
  • 12,209
  • 10
  • 24
  • 44
Vivek Patel
  • 25
  • 2
  • 6

2 Answers2

0

You can have a check with this Notifications in Xamarin.iOS .

iOS applications handle remote and local notifications in almost exactly the same fashion. When an application is running, the ReceivedLocalNotification method or the ReceivedRemoteNotification method on the AppDelegate class will be called, and the notification information will be passed as a parameter.

An application can handle a notification in different ways. For instance, the application might just display an alert to remind users about some event. Or the notification might be used to display an alert to the user that a process has finished, such as synching files to a server.

The following code shows how to handle a local notification and display an alert and reset the badge number to zero:

public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
{
    // show an alert
    UIAlertController okayAlertController = UIAlertController.Create(notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert);
    okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

    Window.RootViewController.PresentViewController(okayAlertController, true, null);

    // reset our badge
    UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
}

In addition , there is a sample you can download to check . It works no matter in Debug or Release Model in my local site (iOS 13.3).

enter image description here

The effect :

enter image description here

Junior Jiang
  • 12,430
  • 1
  • 10
  • 30
  • I have already used the link that you suggested and set-up the code accordingly. I want to set the local notification only when the app is minimized. It is working fine when I am debugging the app through visual studio same as you are doing in the above image (however I am doing with real devices), but when I unplugged the device from system and run the app directly, it is not able to receive the notification, when the app is in minimized code. **I WANT TO RECEIVE THE NOTIFICATION, WHEN APP IS MINIMIZED OR PHONE IS LOCKED.** – Vivek Patel Mar 20 '20 at 11:13
  • Let me give you an example, My app is having chatting functionality and when the app is running in the background and someone sends the message, I want to notify the user by using local notification (not remote notification - as my app is already running in minimized mode). – Vivek Patel Mar 20 '20 at 11:22
  • @VivekPatel Okey , if in chatting functionality , I think you'd better use custom server to send remote notification to device . That will guarantee app will receive notification no matter the device is background or locked . – Junior Jiang Mar 23 '20 at 01:34
  • Jiang, Thanks for the suggestion, I am already aware about the remote push notifications, but my local notifications code is working fine for Android platform, so I want to implement the same local notification for my iOS, but unfortunately, it is not working in case of iOS. So you have any idea of my above-explained issue? – Vivek Patel Mar 23 '20 at 09:02
  • @VivekPatel I have tried with physical device , however can not reproduce it . It works , now I have no idea about this reason :( – Junior Jiang Mar 23 '20 at 09:45
  • @Jiang, I think it is working in your case because, when you send the notification at that time your app is n foreground mode, then you are doing app minimisation, so your code to fire the notification is already executed, so you can able to receive the notification. – Vivek Patel Mar 24 '20 at 12:14
  • I think my issue is relate to Background processing, When I minimized the app the execution of thread appears to be paused and It will be resumed when the application is brought back to the foreground. So you have any idea that how to receive request from server and execute the code even app is in minimized mode? – Vivek Patel Mar 24 '20 at 12:16
  • @VivekPatel You need to mark sure the thread of background work first .Have a look at this :https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-techniques/ios-backgrounding-with-tasks#performing-tasks-during-didenterbackground – Junior Jiang Mar 25 '20 at 01:45
  • Jiang: I have already implemented the code that is given in link - shared by you. But it didn't work for me. I have chat application, when app is minimized and some user sends the message then I want to notify user by implementing local notification. So, it is not like I have some pending task that I want to finish while app goes to background. – Vivek Patel Mar 25 '20 at 07:39
  • @Jiang: In real scenario it is possible that when app is already minimised and some user sends the message then in that case I want to display the local notification. So when app is minimized it never executes the code it pause the execution of thread and resume execution of thread when apps comes to foreground. Note that app is already running so I don’t want to implement the Push notification. So you have any idea about that? – Vivek Patel Mar 25 '20 at 07:42
  • @VivekPatel Sorry for that , I have no idea now . If good point later will share here . – Junior Jiang Mar 25 '20 at 07:52
0

Just add this code in your AppDelegate DidFinishLaunching and notification will start working in the background. BackgroundTask- showNotification may get canceled sometime, for me whenever my dashboard is loaded, I guess as it has multiple API Calls. so add it in your DidEnterBackground Delegate as well with different taskID, to start a new background task. It works fine for me.

nint taskID = yourTaskID;
taskID = application.BeginBackgroundTask("showNotification", expirationHandler: ()=> {
     UIApplication.SharedApplication.EndBackgroundTask(taskID);
});
semeinc
  • 31
  • 4