Tutorial: Send push notifications to Xamarin.iOS apps using Azure Notification Hubs
Overview
This tutorial shows you how to use Azure Notification Hubs to send push notifications to an iOS application. You create a blank Xamarin.iOS app that receives push notifications by using the Apple Push Notification service (APNs).
When you're finished, you are able to use your notification hub to broadcast push notifications to all the devices running your app. The finished code is available in the NotificationHubs app sample.
In this tutorial, you create/update code to do the following tasks:
- Generate the certificate signing request file
- Register your app for push notifications
- Create a provisioning profile for the app
- Configure your notification hub for iOS push notifications
- Send test push notifications
Prerequisites
Azure subscription. If you don't have an Azure subscription, create a free Azure account before you begin.
Latest version of Xcode
An iOS 10 (or later version) compatible device
Apple Developer Program membership.
-
Note
Because of configuration requirements for iOS push notifications, you must deploy and test the sample application on a physical iOS device (iPhone or iPad) instead of in the simulator.
Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Xamarin.iOS apps.
Generate the certificate-signing request file
The Apple Push Notification Service (APNs) uses certificates to authenticate your push notifications. Follow these instructions to create the necessary push certificate to send and receive notifications. For more information on these concepts, see the official Apple Push Notification Service documentation.
Generate the Certificate Signing Request (CSR) file, which Apple uses to generate a signed push certificate.
On your Mac, run the Keychain Access tool. It can be opened from the Utilities folder or the Other folder on the Launchpad.
Select Keychain Access, expand Certificate Assistant, and then select Request a Certificate from a Certificate Authority.
Note
By default, Keychain Access selects the first item in the list. This can be a problem if you're in the Certificates category and Apple Worldwide Developer Relations Certification Authority is not the first item in the list. Make sure you have a non-key item, or the Apple Worldwide Developer Relations Certification Authority key is selected, before generating the CSR (Certificate Signing Request).
Select your User Email Address, enter your Common Name value, make sure that you specify Saved to disk, and then select Continue. Leave CA Email Address blank as it isn't required.
Enter a name for the CSR file in Save As, select the location in Where, and then select Save.
This action saves the CSR file in the selected location. The default location is Desktop. Remember the location chosen for the file.
Next, register your app with Apple, enable push notifications, and upload the exported CSR to create a push certificate.
Register your app for push notifications
To send push notifications to an iOS app, register your application with Apple, and also register for push notifications.
If you haven't already registered your app, browse to the iOS Provisioning Portal at the Apple Developer Center. Sign in to the portal with your Apple ID, and select Identifiers. Then select + to register a new app.
On the Register a New Identifier screen, select the App IDs radio button. Then select Continue.
Update the following three values for your new app, and then select Continue:
Description: Type a descriptive name for your app.
Bundle ID: Enter a Bundle ID of the form Organization Identifier.Product Name as mentioned in the App Distribution Guide. The Organization Identifier and Product Name values must match the organization identifier and product name you use when you create your Xcode project. In the following screenshot, the NotificationHubs value is used as an organization identifier and the GetStarted value is used as the product name. Make sure the Bundle Identifier value matches the value in your Xcode project, so that Xcode uses the correct publishing profile.
Push Notifications: Check the Push Notifications option in the Capabilities section.
This action generates your App ID and requests that you confirm the information. Select Continue, then select Register to confirm the new App ID.
After you select Register, you see the new App ID as a line item in the Certificates, Identifiers & Profiles page.
In the Certificates, Identifiers & Profiles page, under Identifiers, locate the App ID line item that you just created, and select its row to display the Edit your App ID Configuration screen.
Creating a Certificate for Notification Hubs
A certificate is required to enable the notification hub to work with APNS. This can be done in one of two ways:
- Create a .p12 that can be uploaded directly to Notification Hub.
- Create a .p8 that can be used for token-based authentication (the newer approach).
The newer approach has a number of benefits (compared to using certificates) as documented in Token-based (HTTP/2) authentication for APNS. However, steps have been provided for both approaches.
OPTION 1: Creating a .p12 push certificate that can be uploaded directly to Notification Hub
Scroll down to the checked Push Notifications option, and then select Configure to create the certificate.
The Apple Push Notification service SSL Certificates window appears. Select the Create Certificate button under the Development SSL Certificate section.
The Create a new Certificate screen is displayed.
Note
This tutorial uses a development certificate, which your app uses to generate a unique device token. The same process is used when registering a production certificate. Just make sure that you use the same certificate type when sending notifications.
Select Choose File, browse to the location where you saved the CSR file from the first task, and then double-click the certificate name to load it. Then select Continue.
After the portal creates the certificate, select the Download button. Save the certificate, and remember the location to which it's saved.
The certificate is downloaded and saved to your computer in your Downloads folder.
Note
By default, the downloaded development certificate is named aps_development.cer.
Double-click the downloaded push certificate aps_development.cer. This action installs the new certificate in the Keychain, as shown in the following image:
Note
Although the name in your certificate might be different, the name will be prefixed with Apple Development iOS Push Services.
In Keychain Access, right-click the new push certificate that you created in the Certificates category. Select Export, name the file, select the .p12 format, and then select Save.
You can choose to protect the certificate with a password, but this is optional. Click OK if you want to bypass password creation. Make a note of the file name and location of the exported .p12 certificate. They are used to enable authentication with APNs.
Note
Your .p12 file name and location might be different than what is pictured in this tutorial.
OPTION 2: Creating a .p8 certificate that can be used for token-based authentication
Make note of the following details:
- App ID Prefix (this is a Team ID)
- Bundle ID
Back in Certificates, Identifiers & Profiles, click Keys.
Note
If you already have a key configured for APNS, you can re-use the .p8 certificate that you downloaded right after it was created. If so, you can ignore steps 3 through 5.
Click the + button (or the Create a key button) to create a new key.
Provide a suitable Key Name value, then check the Apple Push Notifications service (APNs) option, and then click Continue, followed by Register on the next screen.
Click Download and then move the .p8 file (prefixed with AuthKey_) to a secure local directory, then click Done.
Note
Be sure to keep your .p8 file in a secure place (and save a backup). After downloading your key, it cannot be re-downloaded as the server copy is removed.
On Keys, click on the key that you just created (or an existing key if you have chosen to use that instead).
Make note of the Key ID value.
Open your .p8 certificate in a suitable application of your choice such as Visual Studio Code then make note of the key value. This is the value between -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- .
-----BEGIN PRIVATE KEY----- <key_value> -----END PRIVATE KEY-----
Note
This is the token value that will be used later to configure Notification Hub.
At the end of these steps you should have the following information for use later in Configure your notification hub with APNs information:
- Team ID (see step 1)
- Bundle ID (see step 1)
- Key ID (see step 7)
- Token value i.e. the .p8 key value (see step 8)
Create a provisioning profile for the app
Return to the iOS Provisioning Portal, select Certificates, Identifiers & Profiles, select Profiles from the left menu, and then select + to create a new profile. The Register a New Provisioning Profile screen appears.
Select iOS App Development under Development as the provisioning profile type, and then select Continue.
Next, select the app ID you created from the App ID drop-down list, and select Continue.
In the Select certificates window, select the development certificate that you use for code signing, and select Continue. This certificate isn't the push certificate you created. If one does not exist, you must create it. If a certificate does exist, skip to the next step. To create a development certificate if one does not exist:
- If you see No Certificates are available, select Create Certificate.
- In the Software section, select Apple Development. Then select Continue.
- In the Create a New Certificate screen, select Choose File.
- Browse to the Certificate Signing Request certificate you created earlier, select it, and then select Open.
- Select Continue.
- Download the development certificate, and remember the location to which it's saved.
Return to the Certificates, Identifiers & Profiles page, select Profiles from the left menu, and then select + to create a new profile. The Register a New Provisioning Profile screen appears.
In the Select certificates window, select the development certificate that you just created. Then select Continue.
Next, select the devices to use for testing, and select Continue.
Finally, choose a name for the profile in Provisioning Profile Name, and select Generate.
When the new provisioning profile is created, select Download. Remember the location to which it's saved.
Browse to the location of the provisioning profile, and then double-click it to install it on your Xcode development machine.
Create a notification hub
In this section, you create a notification hub and configure authentication with APNs by using either the .p12 push certificate or token-based authentication. If you want to use a notification hub that you've already created, you can skip to step 5.
Sign in to the Azure portal.
Select All services on the left menu.
Type Notification Hubs in the Filter services text box. Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. Select Notification Hubs.
On the Notification Hubs page, select Create on the toolbar.
In the Basics tab on the Notification Hub page, do the following steps:
In Subscription, select the name of the Azure subscription you want to use, and then select an existing resource group, or create a new one.
Enter a unique name for the new namespace in Namespace Details.
A namespace contains one or more notification hubs, so type a name for the hub in Notification Hub Details.
Select a value from the Location drop-down list box. This value specifies the location in which you want to create the hub.
Review the Availability Zones option. If you chose a region that has availability zones, the check box is selected by default. Availability Zones is a paid feature, so an additional fee is added to your tier.
Choose a Disaster recovery option: None, Paired recovery region, or Flexible recovery region. If you choose Paired recovery region, the failover region is displayed. If you select Flexible recovery region, use the drop-down to choose from a list of recovery regions.
Select Create.
When the deployment is complete select Go to resource.
Configure your notification hub with APNs information
Under Notification Services, select Apple (APNS) then follow the appropriate steps based on the approach you chose previously in the Creating a Certificate for Notification Hubs section.
Note
If you build your app with App Store or Ad-Hoc distribution profile, use the Production for Application Mode. This will allow your device to send push notifications to users who purchased your app from the store.
OPTION 1: Using a .p12 push certificate
Select Certificate.
Select the file icon.
Select the .p12 file that you exported earlier, and then select Open.
If required, specify the correct password.
Select Sandbox mode.
Select Save.
OPTION 2: Using token-based authentication
Select Token.
Enter the following values that you acquired earlier:
- Key ID
- Bundle ID
- Team ID
- Token
Choose Sandbox
Select Save.
You've now configured your notification hub with APNs. You also have the connection strings to register your app and send push notifications.
Connect your app to the notification hub
Create a new project
In Visual Studio, create a new iOS project and select the Single View App template, and click Next
Enter your App Name and Organization identifier, then click Next, then Create
From the Solution view, double-click Info.plist and under Identity make sure your Bundle Identifier matches the one used when creating your provisioning profile. Under Signing ensure that your Developer account is selected under Team, "Automatically manage signing" is selected and your Signing Certificate and Provisioning Profile are automatically selected.
From the Solution view, double-click the
Entitlements.plist
and ensure that Enable Push Notifications is checked.Add the Azure Messaging package. In the Solution view, right-click the project and select Add > Add NuGet Packages. Search for Xamarin.Azure.NotificationHubs.iOS and add the package to your project.
Add a new file to your class, name it
Constants.cs
and add the following variables and replace the string literal placeholders with thehubname
and theDefaultListenSharedAccessSignature
noted earlier.// Azure app-specific connection string and hub path public const string ListenConnectionString = "<Azure DefaultListenSharedAccess Connection String>"; public const string NotificationHubName = "<Azure Notification Hub Name>";
In
AppDelegate.cs
, add the following using statement:using WindowsAzure.Messaging.NotificationHubs; using UserNotifications
Create an implementation of the
MSNotificationHubDelegate
in theAppDelegate.cs
:public class AzureNotificationHubListener : MSNotificationHubDelegate { public override void DidReceivePushNotification(MSNotificationHub notificationHub, MSNotificationHubMessage message) { } }
In
AppDelegate.cs
, updateFinishedLaunching()
to match the following code:public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Set the Message listener MSNotificationHub.SetDelegate(new AzureNotificationHubListener()); // Start the SDK MSNotificationHub.Start(ListenConnectionString, NotificationHubName); return true; }
In
AppDelegate.cs
, implement theDidReceivePushNotification
method for theAzureNotificationHubListener
class:public override void DidReceivePushNotification(MSNotificationHub notificationHub, MSNotificationHubMessage message) { // This sample assumes { aps: { alert: { title: "Hello", body: "World" } } } var alertTitle = message.Title ?? "Notification"; var alertBody = message.Body; var myAlert = UIAlertController.Create(alertTitle, alertBody, UIAlertControllerStyle.Alert); myAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(myAlert, true, null); }
Run the app on your device.
Send test push notifications
You can test receiving notifications in your app with the Test Send option in the Azure portal. It sends a test push notification to your device.
Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. If a library is not available for your back-end, you can also use the REST API directly to send notification messages.
Next steps
In this tutorial, you sent broadcast notifications to all your iOS devices registered with the backend. To learn how to push notifications to specific iOS devices, advance to the following tutorial: