Working example Push notification (using azure notification hubs) for Xamarin.Forms iOS project?

Hi everyone,

For the last few weeks I have tried Fruitlessly with Push notification for Xamarin.iOS with my Xamarin.Forms portable project. It appears notifications get sent successfully from azure but they never get received to the device.

My code is provided below for the AppDelegate class. I have followed this tutorial: https://azure.microsoft.com/en-us/documentation/articles/xamarin-notification-hubs-ios-push-notification-apns-get-started/ and I have downloaded the Azure Messaging Component from the Xamarin components download, it did appear that version 1.2.5.0 was incomplete and had errors and thankfully this seems to be fixed with version 1.2.5.2 but even still I'm unable to receive push notifications.

The permission pop up shows, I can successfully register devices, i have enabled push notifications in background modes. I have generated the development certificate and exported the .p12 file and uploaded it for sandbox development for azure and I setup my app id on apple.developer.com with push notifications enabled with the correct provision profile installed. Since the notifications send successfully from azure but don't show up on my iPhone device I think it might be a code issue or some other deep rooted issues.

  public override void RegisteredForRemoteNotifications(UIApplication app, NSData deviceToken) {

   // Get current device token
   var DeviceToken = deviceToken.Description;
   if (!string.IsNullOrWhiteSpace(DeviceToken)) {
    DeviceToken = DeviceToken.Trim('<').Trim('>');
    DeviceToken = DeviceToken.Replace(" ", String.Empty);
   }

   // Get previous device token
   var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

   // Has the token changed?
   //  if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
   {

    var cs = SBConnectionString.CreateListenAccess(
     new NSUrl("sb://#myhubname#.servicebus.windows.net/"),
     "#listenkey#");

    // Register our information with Azure
    var hub = new SBNotificationHub(cs, "#myhubname#");

    hub.RegisterNativeAsync(DeviceToken, null, err => {
     if (err != null) {
      Console.WriteLine("Error: " + err.Description);
     } else {
      Console.WriteLine("Success");
     }
    });
   }
   NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
  }

In my finished launching I also have this:

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);
} 

and lastly

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action < UIBackgroundFetchResult > completionHandler) {
 Console.WriteLine("PushData received " + userInfo.ToString());
 ProcessNotification(userInfo, false);
 completionHandler(UIBackgroundFetchResult.NewData);
}

Id really appreciate it if someone could provide some working example of push notifications for xamarin.ios. And any other configuration setup in their project.

Thanks!

Posts

  • estebanhedezestebanhedez MXUniversity
    edited November 2016

    I have similar issue and also try both Dev Provision Profile / Production Provision Profile each one with the corresponding p12 (sandbox/production), the azure hub register the device but when I sent the notification only my android devices recived the notification.

    In my case I used a SharedListen on the device and Full on Backend WebApi that send the notification.

    /Shared
    INotificationHubsService
            public interface INotificationHubsService
                {
                    string PnsHandler { get; set; }
    
                    void Init(object context);
    
                    void RegisterOrUpdate();
    
                }
    

    /iOS
    public class NotificationHubsService : INotificationHubsService
    {
    private readonly SBNotificationHub _hub;

                public NotificationHubsService()
                {
                    // register device in notification hubs
                    string hubName = Constants.K_AZ_HUB_NAME;
                    string hubConnectionString = Constants.K_AZ_HUB_CONNECTION;
    
                    _hub = new SBNotificationHub(hubConnectionString, hubName);
                }
    
                public string PnsHandler { get; set; }
    
                public void Init(object context)
                {
    
                }
    
                public void RegisterOrUpdate()
                {
                    var settingsService = ServiceLocator.Current.GetInstance<ISettingsService>();
                    // create tags if you want
                    var tags = new NSSet(settingsService.Tags.ToArray());
    
                    //PnsHandler = ((AppDelegate)UIApplication.SharedApplication.Delegate).DeviceToken;
    
                    _hub.UnregisterAllAsync(PnsHandler, (error) => {
                        if (error != null)
                        {
                            Console.WriteLine("Error calling Unregister: {0}", error.ToString());
                            return;
                        }
    
                        _hub.RegisterNativeAsync(PnsHandler, tags, (errorCallback) => {
                            if (errorCallback != null)
                                Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
                        });
                    });
                }
            }
    

    /Backend-WebApi
    private async Task SendNotificationAsync(string message, string type, string id, string tag)
    {
    try
    {
    Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.ConnectionStrings["MS_NotificationHubConnectionString"].ConnectionString, ConfigurationManager.AppSettings["MS_NotificationHubName"]);
    try
    {
    // Windows 8.1 / Windows Phone 8.1
    var toast = @"" + message + "";
    outcome = await hub.SendWindowsNativeNotificationAsync(toast, tag);
    }
    catch { }

                            try
                            {
                                // iOS
                                var alert = "{\"aps\":{\"alert\":\"" + message + "\", \"title\":\"" + type + "\", \"id\": \"" + id + "\"}}";
                                outcome = await hub.SendAppleNativeNotificationAsync(alert, tag);
                            }
                            catch {  }
    
                            try
                            {
                                // Android
                                var notif = "{ \"data\" : {\"message\":\"" + message + "\",\"title\":\"" + type + "\",\"id\":\"" + id + "\"}}";
                                outcome = await hub.SendGcmNativeNotificationAsync(notif, tag);
                            }
                            catch { }
                        }
                        catch (Exception ex)
                        {
                            Services.Log.Error(ex);
                            throw ex;
                        }
                    }
    
  • JamesMontemagnoJamesMontemagno USForum Administrator, Xamarin Team, Developer Group Leader Xamurai

    I have all the code for the Evolve app here: http://github.com/xamarinhq/app-evolve that might be good reference.

  • estebanhedezestebanhedez MXUniversity

    thank you @JamesMontemagno

  • DevTeamCubesysDevTeamCubesys USMember
    edited January 2017

    Hi, I need to register for push notifications and later add tags to my registration. Documentation is a nightmare, I'm still confused if I can do this operation on the client or I need to add some custom methods on my backend api.

    From the code above it seems I can do it on the client using NotificationHubClient.CreateClientFromConnectionString(...); what library/package is it? I'm using the Microsoft.Azure.Mobile.Client nuget package in my droid app (Xamarin.Forms), but there are no methods to manage tags.

    Thanks,
    David

  • MarkRadacz.7953MarkRadacz.7953 USInsider, University, Developer Group Leader ✭✭
    edited April 2017

    @DevTeamCubesys NotificationHubClient is in the package Microsoft.Azure.NotificationHubs

Sign In or Register to comment.