Search code examples
c#azurexamarinapple-push-notificationsazure-notificationhub

Sending push notifications through azure notification hubs apns


I have a Xamarin forms app that runs this code for IOS in the AppDelegate.cs file

 public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            Hub = new SBNotificationHub(WBUtility.ListenConnectionString, WBUtility.NotificationHubName);

            Hub.UnregisterAllAsync(deviceToken, (error) => {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
                    return;
                }

                NSSet tags = null; // create tags if you want
                Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
                    if (errorCallback != null)
                        System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
                });
            });


}

So it looks like this code just registers the device on the notification hub which is good but I want to send individual users notifications. The documentation shows code in objective c which I don't understand. Basically I would think that every time the user logs into my app on the client side I should get his device token and map it to his username on the backend but I don't know if this is the right way to go about it. So how do I map a user to a registered ios device then send a notification to all the registered ios devices that the user is logged in on?


Solution

  • If you want to send notifications to existing users, I suggest making use of Notification Hub tags when you register the user. If you do not have a mapping between users and devicetokens, you can retroactively map this over time as users login in (as you suggested).

    So if your user BobBarker has device ID abcdef01234567890 and a unique ID within your database of 29817, you could create a tag attached to the user's notification hub registration of "user_29817". Then when you want to address this user individually, you can send a request to the notification hub to message all users with the tag "user_29817".