Here is a sample code that shows how to display a pop-up warning in Xamarin.Forms when you receive a push notification on any of the platforms.
Generic Xamarin.Forms Code
Create static classin the generic code Xamarin.Forms that runs DisplayAlert. Then create a method staticcalled ShowAlertthat can be accessed from our platform-oriented projects.
public static class PushNotificationHelpers
{
public static async Task ShowAlert(string alert)
{
await Application.Current?.MainPage?.DisplayAlert("Push Notification Received", alert, "OK");
}
}
iOS AppDelegate
Push Notification iOS, ReceivedRemoteNotification AppDelegate. ReceivedRemoteNotification , iOS push-.
[Register("AppDelegate")]
public partial class AppDelegate : FormsApplicationDelegate
{
.
.
.
public override async void ReceivedRemoteNotification(UIApplication app, NSDictionary userInfo)
{
await ProcessNotification(userInfo);
}
async Task ProcessNotification(NSDictionary userInfo)
{
if (userInfo == null)
return;
Console.WriteLine("Received Notification");
var apsKey = new NSString("aps");
if (userInfo.ContainsKey(apsKey))
{
var alertKey = new NSString("alert");
var aps = (NSDictionary)userInfo.ObjectForKey(apsKey);
if (aps.ContainsKey(alertKey))
{
var alert = (NSString)aps.ObjectForKey(alertKey);
await PushNotificationHelpers.ShowAlert(alert.ToString());
Console.WriteLine("Notification: " + alert);
}
}
}
}
Android GcmServiceBase
push- Android, , GcmServiceBase OnMessage. OnMessage , Android .
[Service(Name="com.sample.evolve.GcmService")]
public class GcmService : GcmServiceBase
{
.
.
.
protected override void OnMessage (Context context, Intent intent)
{
Console.WriteLine ("Received Notification");
try
{
if (intent != null || intent.Extras != null)
{
var keyset = intent.Extras.KeySet ();
foreach (var key in keyset)
{
var message = intent.Extras.GetString(key);
Console.WriteLine("Key: {0}, Value: {1}", key, message);
if(key == "message")
await PushNotificationHelpers.ShowAlert(message);
}
}
}
catch(Exception ex)
{
Console.WriteLine ("Error parsing message: " + ex);
}
}
}
Xamarin Evolve , Push- Xamarin.Forms. Xamarin Evolve, .