local notification is not displayed - ios

I'm working on a Xamarion iOS app. I want to display a local notification when an event occurs in my app, Like Outlook does when an email is received.
I'm using the following code, after having received the right to send notification from the user, of course:
var content = new UNMutableNotificationContent();
if (!string.IsNullOrWhiteSpace(value: mySoundFile))
{
content.Sound = UNNotificationSound.GetCriticalSound(mySoundFile);
}
if (!string.IsNullOrEmpty(myChannelDescription))
{
content.ThreadIdentifier = myChannelDescription;
}
content.Title = "MyTitle";
content.Body = "MyText";
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
var request = UNNotificationRequest.FromIdentifier(notification.Id.ToString(), content, trigger);
var center = UNUserNotificationCenter.Current;
center.AddNotificationRequest(request, null);
But the notification is not displayed.
Any help appreciated.

The reason for not displaying the notification could be several things. Try the following solutions:
Make sure that the application has the required rights to send notifications and that the user has enabled them.
Check if the sound file is valid and located in the application package. It may also be necessary to add it to the Info.plist file.
Check if the thread identifier is valid and not repeatable.
Check if the trigger time is valid. Setting 0.1 seconds is very short and may not be enough to display the notification.
If the above solutions do not work, it is worth using debugging tools to more closely examine why the notification is not displayed.

On iOS, you must request permission to use notifications before attempting to schedule them. Just like this, you can try to check if the following code is added to your project:
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
{
...
});
You can change your AddNotificationRequest as follows to see if there is an error in the notification:
center.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
throw new Exception($"Failed to schedule notification: {err}");
}
});
For more details, you can refer to the following documents to check some permission issues:
Enhanced User Notifications in Xamarin.iOS | Microsoft
Asking permission to use notifications | Apple Developer
UpDate: If your app is in the foreground. You could try implementing the delegate userNotificationCenter(_:willPresent:withCompletionHandler:) which will be called when a notification arrives while the app is in the foreground. Refer to the following code:
UNUserNotificationCenter.Current.Delegate = new TestDelegate();
public class TestDelegate: UNUserNotificationCenterDelegate
{
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
completionHandler(UNNotificationPresentationOptions.Alert);
}
}

Related

IOS 13 doesn't play a notification sound using FirebasePushNotificationPlugin

I use Firebase to push notifications to the users at a certain time. They receive the notification but no alert sound is played. In the settings, the allow sound/notifications are turned on and other IOS13 and other apps play sound.
Version Number of FirebasePushNotificationPlugin Plugin: 3.3.10
Device Tested On: iphone X, OS: 13.4.1
Simulator Tested On: N/A (simulators don't receive notifications)
Version of VS: VS for Mac Community, 8.6.6 (build 11)
Version of Xamarin: Xamarin.IOS 13.18.2.1, Xamarin.Forms v4.6.0.847
AppDelegate.cs:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
bool fbaseStarted = false;
try
{
// This method does all the UNUserNotificationCenter.Current.RequestAuthorization() code so we don't have to.
FirebasePushNotificationManager.Initialize(options, true);
fbaseStarted = true;
}
catch
{ }
LoadApplication(new App());
if (!fbaseStarted)
{
try
{
FirebasePushNotificationManager.Initialize(options, true);
}
catch { }
}
FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Badge | UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound;
}
Within one of the pages of my code, I subscribe a list of tags (please note that I unsubscribe because the first time the code runs it fails silently if the notifications aren't approved - resulting in the model thinking the notifications was subscribed when it wasn't):
CrossFirebasePushNotification.Current.UnsubscribeAll();
CrossFirebasePushNotification.Current.Subscribe(Constants.NotificationTagsArray);
I keep coming across payload json solutions but unless I am wrong, I don't think that applies to me as I am using Xamarin and the FirebasePushNotificationPlugin. Is there any additional permissions that were added in ios 13 for playing notifications with sound that I have missed?
I have also posted here: https://github.com/CrossGeeks/FirebasePushNotificationPlugin/issues/348 but nobody has been able to assist me yet.
Thanks
The issue actually lies with the sending of the notifications nothing to do with the Xamarin App. The issue resided in the services that sends the notifications to firebase (to then be sent out to the phones).
In the service we were sending a FirebaseNet.Messaging.Message() to the phones:
Message FireBasemessage = new Message()
{
To = "/topics/" + PushNote.Tag,
TimeToLive = 86400,
Priority = MessagePriority.high,
ContentAvailable = true,
Notification = new AndroidNotification()
{
Tag = "/topics/" + PushNote.Tag,
Body = enhancedMessage,
Title = xtitle,
}
,
Data = new Dictionary<string, string>
{
{ "param", PushNote.Tag },
{ "text", enhancedMessage}
}
};
In the AndroidNotification() object required Sound = "default" to be added for it to work. Please note that this works for both Android and IOS notifications despite the fact it is an AndroidNotification object.

Register for notifications (FCM) outside AppDelegate

I want to ask the user to allow notifications only when we prompt the "AskNotification" view and when he click on "Yes".
In order to do that, I did the following :
public static AppDelegate Self { get; private set; }
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
HtmlLabelRenderer.Initialize();
global::Xamarin.Forms.Forms.Init();
// Notifications
Firebase.Core.App.Configure();
//AllowNotifications();
...
LoadApplication(new App());
AppDelegate.Self = this;
return base.FinishedLaunching(app, options);
}
public void AllowNotifications()
{
//In iOS you must request permission to show local / remote notifications first since it is a user interrupting action.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// Request Permissions
UNUserNotificationCenter.Current.RequestAuthorization(
UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
(granted, error) =>
{
// Do something if needed
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
Messaging.SharedInstance.Delegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert
| UIUserNotificationType.Badge
| UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings
.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
Console.WriteLine("-------- RegisterForRemoteNotifications");
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
And then on my Code Behind when the user click on the "Allow" button (from my view) I do the following :
AppDelegate appDelegate = AppDelegate.Self;
appDelegate.AllowNotifications();
As you can see, I'm using the Singleton pattern to have an access to the AppDelegate. My problem is when the "AllowNotifications" is called inside the AppDelegate (it's commented on the code above), the system prompt ask for the user and notifications are received.
But when I call the AllowNotification method from another page with the Singleton pattern. The system popup is showing, we the user click "Yes" it allow notification on iOS parameters. But I never get into my "DidReceiveMessage" method.
Thanks for your help
This issue has nothing to do with your code.It is an expected behavior.Because you used firebase (Xamarin.Firebase.iOS.CloudMessaging from NuGet).
For devices running iOS 10 and above, you must assign your delegate object to the UNUserNotificationCenter object to receive display notifications, and the FIRMessaging object to receive data messages, before your app finishes launching. For example, in an iOS app, you must assign it in the method FinishedLaunching.
That is to say,when you register for notifications out the method FinishedLaunching,even if system popup showed,the register will still not working.
For more detail you can refer here.

iOS RemoveDeliveredNotifications(string[] identifier) will not delete the notification(s) when app in background

maybe someone can help me.
In my app I'm using push notifications to inform the users that a new message is written to the database. One user can accept the notification and work with the content or dismiss it. If the user accepts it, a silent push is sent to all other devices which received the notification earlier. Here is my code handling this silent notification:
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary remoteNotification)
{
try
{
if (remoteNotification != null)
{
var alert = remoteNotification[FromObject("aps")];
if (alert != null)
{
string id = ((NSDictionary)alert)[FromObject("deleteId")].Description;
if (!String.IsNullOrEmpty(id))
{
List<string> idents = new List<string>();
UNUserNotificationCenter.Current.GetDeliveredNotifications(completionHandler: (UNNotification[] t) =>
{
foreach (UNNotification item in t)
{
UNNotificationRequest curRequest = item.Request;
var notificationId = ((NSDictionary)curRequest.Content.UserInfo[FromObject("aps")])[FromObject("notificationId")].Description;
if (id == notificationId)
{
idents.Add(curRequest.Identifier);
}
}
UNUserNotificationCenter.Current.RemoveDeliveredNotifications(idents.ToArray());
});
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
The problem is that the notification is still visible in the notification center until the app is brought to foreground. But then it gets deleted.
Is there a way to force the method to delete the notification instantly and not only when the app is (re)opened?
When you want to clear the Notifications send from this app. Set its application's badge to 0 to achieve this.
As you said you send a silent notifications to other users, Then DidReceiveRemoteNotification() will fire. In this event we can clear all notifications:
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
var aps = userInfo["aps"] as NSDictionary;
if (aps["content-available"].ToString() == "1")
{
//check if this is a silent notification.
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
}
completionHandler(UIBackgroundFetchResult.NewData);
}
Please notice that starting with iOS 8.0, your application needs to register for user notifications to be able to set the application icon badge number. So please add the code below in FinishedLaunching():
UIUserNotificationSettings settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Badge, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
Moreover silent notifications can only be received when your app is on background or foreground. If it's terminated, this will fail.
To remove a notification, you send a silent push notification to all devices with the notification ID as payload that should be removed.
On the clients you implement a UNNotificationServiceExtension which allows you to remove currently displayed notifications by their IDs: UNUserNotificationCenter.current().removeDeliveredNotifications.
This gives you the advantage that you have full control over this logic on the server side.

How can I know when UNUserNotificationCenter's removeAllPendingNotificationRequests() has completed?

The iOS docs say that UNUserNotificationCenter's removeAllPendingNotificationRequests() is asynchronous.
What I want to do is this:
Call removeAllPendingNotificationRequests() to get rid of all my scheduled notifications
Schedule a bunch of new notifications, some of which may or may not have the same IDs as what was there previously
But since the documentation says that the method is asynchronously running on another thread (and there is no completion callback parameter) I'm worried that sometimes, depending on the vagaries of threads and timing and whatnot, that step #1 will still be going as I am creating things in step 2 and therefore it will also kill some of the new notifications I'm making.
This kind of stuff is a little tricky to test manually, since it depends on timing. So I'm curious is anyone knows if this is something I should be worried about or not...
In documentation for add notification I found this:
Calling -addNotificationRequest: will replace an existing notification
request with the same identifier.
Maybe the solution would be something like this:
Create new notification requests
Get all pending and filter out only the ones that will not be replaced
Delete not replaced
Add all new notifications
let center = UNUserNotificationCenter.current()
// Create new requests
let newRequests: [UNNotificationRequest] = [...]
let identifiersForNew: [String] = newRequests.map { $0.identifier }
center.getPendingNotificationRequests { pendingRequests in
// Get all pending notification requests and filter only the ones that will not be replaced
let toDelete = pendingRequests.filter { !identifiersForNew.contains($0.identifier) }
let identifiersToDelete = toDelete.map { $0.identifier }
// Delete notifications that will not be replaced
center.removePendingNotificationRequests(withIdentifiers: identifiersToDelete)
// Add all new requests
for request in newRequests {
center.add(request, withCompletionHandler: nil)
}
}
I have the same case as you and up to know I don't have a problem with this code:
center.getPendingNotificationRequests(completionHandler: { notifications in
var notificationIds:[String] = []
for notification in notifications {
if notification.identifier != "something_taht_I_dont_dismiss"{
notificationIds.append(notification.identifier)
}
}
self.center.removePendingNotificationRequests(withIdentifiers: notificationIds)
createAllNewNotifications()
})
If you want to double check all if the pending notifications are removed you can create simple recursion method for checking.
func removeAllNotificationsSafe() {
center.removeAllPendingNotificationRequests()
checkNotificationsAreRemoved()
}
func checkNotificationsAreRemoved() {
center.getPendingNotificationRequests(completionHandler: { notifications in
if notifications.count > 0 {
self.checkNotificationsAreRemoved()
} else {
self.doWhathverYouWant()
}
}
}
I don't believe this is needed, because all the actions of UNUserNotificationCenter will be synchronized between each other.

Android Xamarin Notification builder setWhen not working

I am trying to implement local push notification in Xamarin Forms. I am using DependencyService to get the Android implementation of notification.
Here is the code I am using to push a notification at a particular time:
public void SetNotification(DateTime notificationDate, TimeSpan notificationTime)
{
long dateInMilli = (long)(notificationDate.Add(notificationTime) - DateTime.MinValue).TotalMilliseconds;
Notification.Builder builder = new Notification.Builder(Xamarin.Forms.Forms.Context)
.SetContentTitle("Test Notification")
.SetContentText("Notification from Xamarin Forms")
.SetSmallIcon(Resource.Drawable.icon)
.SetDefaults(NotificationDefaults.Sound)
.SetWhen(dateInMilli);
Notification notification = builder.Build();
NotificationManager notificationManager =
(NotificationManager)Forms.Context.GetSystemService(Context.NotificationService);
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
The problem is, notification is showing instantaneously not as per date and time set by SetWhen(dateInMilli).
SetWhen is used to display the time you put onto the timestamp of the notification, not to send the notification after X. You'll have to use alarms for that.
Refer to this to learn about that class.

Resources