TobiasBuchholz / Plugin.Firebase

Wrapper around the native Android and iOS Firebase Xamarin SDKs
MIT License
213 stars 49 forks source link

Data notifications on iOS #310

Open marktopley opened 3 months ago

marktopley commented 3 months ago

Hi,

Whilst trying to get foreground data notifications to our iOS app I was only able to get this working on Android, in fact Android required no work to get it working.

Thanks to https://stackoverflow.com/questions/74772253/net-maui-ios-app-with-silent-push-notifications-receivedremotenotification-or-d for the fix.

Can this please be integrated into the library please.

Using Plugin.Firebase we've had notifications functional on iOS and Android provided they contain a Notification element.

I have only had issues when I didn't want a Notification to be shown and the notification only to be data and handled in the foreground to refresh the UI when data has changed.

I have added this method to my AppDelegate.cs:

    private static Dictionary<string, string> ToDictionary(NSDictionary dictionary)
    {
        return dictionary.ToDictionary((KeyValuePair<NSObject, NSObject> x) => x.Key.ToString(), (KeyValuePair<NSObject, NSObject> x) => x.Value.ToString());
    }

    //App is in the foreground
    [Foundation.Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")]
    public void DidReceiveRemoteNotification(UIKit.UIApplication application, Foundation.NSDictionary userInfo, Action<UIKit.UIBackgroundFetchResult> completionHandler)
    {
        ILogger<AppDelegate> logger = IPlatformApplication.Current.Services.GetRequiredService<ILogger<AppDelegate>>();
        logger.LogInformation("DidReceiveRemoteNotification: ");

        var instance = (FirebaseCloudMessagingImplementation)CrossFirebaseCloudMessaging.Current;

        var fcmNotification = new FCMNotification(string.Empty, String.Empty, null, ToDictionary(userInfo));
        instance.OnNotificationReceived(fcmNotification);

        completionHandler(UIBackgroundFetchResult.NewData);
    }

And this to my csproj file:

<PropertyGroup>
    <MtouchExtraArgs>--optimize:-static-block-to-delegate-lookup</MtouchExtraArgs>
    <CodesignKey>iPhone Developer</CodesignKey>
</PropertyGroup>

And now data notifications are working with no other changes required.

AdamEssenmacher commented 3 months ago

What do you mean by "integrated into the library"? Like, into the documentation? Or something else?