Skip to content

Commit ae0a1a1

Browse files
committed
code fixes, and markdig formatting fixes
also addresses https://github.com/MicrosoftDocs/azure-docs/issues/6162
1 parent 19c4292 commit ae0a1a1

File tree

1 file changed

+107
-112
lines changed

1 file changed

+107
-112
lines changed
Lines changed: 107 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: Push notifications to Xamarin.iOS apps using Azure Notification Hubs | Microsoft Docs
3-
description: In this tutorial, you learn how to use Azure Notification Hubs to send push notifications to a Xamarin iOS application.
3+
description: In this tutorial, you learn how to use Azure Notification Hubs to send push notifications to a Xamarin.iOS application.
44
services: notification-hubs
55
keywords: ios push notifications,push messages,push notifications,push message
66
documentationcenter: xamarin
@@ -15,31 +15,32 @@ ms.tgt_pltfrm: mobile-xamarin-ios
1515
ms.devlang: dotnet
1616
ms.topic: tutorial
1717
ms.custom: mvc
18-
ms.date: 04/14/2018
18+
ms.date: 08/23/2018
1919
ms.author: dimazaid
20-
2120
---
2221
# Tutorial: Push notifications to Xamarin.iOS apps using Azure Notification Hubs
22+
2323
[!INCLUDE [notification-hubs-selector-get-started](../../includes/notification-hubs-selector-get-started.md)]
2424

2525
## Overview
26-
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)](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html).
26+
27+
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)](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html).
2728

2829
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][GitHub] sample.
2930

30-
In this tutorial, you create/update code to do the following tasks:
31+
In this tutorial, you create/update code to do the following tasks:
3132

3233
> [!div class="checklist"]
3334
> * Generate the certificate signing request file
3435
> * Register your app for push notifications
3536
> * Create a provisioning profile for the app
3637
> * Configure your notification hub for iOS push notifications
37-
> * Send test push notificaitons
38+
> * Send test push notifications
3839
3940
## Prerequisites
4041

4142
- **Azure subscription**. If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin.
42-
- Latest version of [XCode][Install Xcode]
43+
- Latest version of [Xcode][Install Xcode]
4344
- An iOS 10 (or later version) compatible device
4445
- [Apple Developer Program](https://developer.apple.com/programs/) membership.
4546
- [Visual Studio for Mac]
@@ -52,14 +53,16 @@ Completing this tutorial is a prerequisite for all other Notification Hubs tutor
5253
[!INCLUDE [Notification Hubs Enable Apple Push Notifications](../../includes/notification-hubs-enable-apple-push-notifications.md)]
5354

5455
## Configure your notification hub for iOS push notifications
56+
5557
This section walks you through the steps to create a new notification hub and configure authentication with APNS using the **.p12** push certificate that you previously created. If you want to use a notification hub that you have already created, you can skip to step 5.
5658

5759
[!INCLUDE [notification-hubs-portal-create-new-hub](../../includes/notification-hubs-portal-create-new-hub.md)]
5860

5961
### Configure iOS settings for the notification hub
60-
1. Select **Apple (APNS)** in the **NOTIFICATION SETTINGS** group.
61-
2. Select **Certificate**, click the **file** icon, and select the **.p12** file that you exported earlier.
62-
3. Specify the **password** for the certificate.
62+
63+
1. Select **Apple (APNS)** in the **NOTIFICATION SETTINGS** group.
64+
2. Select **Certificate**, click the **file** icon, and select the **.p12** file that you exported earlier.
65+
3. Specify the **password** for the certificate.
6366
4. Select **Sandbox** mode. Use the **Production** mode only if you want to send push notifications to users who purchased your app from the store.
6467

6568
![Configure APNS in Azure portal][6]
@@ -69,9 +72,11 @@ This section walks you through the steps to create a new notification hub and co
6972
Your notification hub is now configured to work with APNS, and you have the connection strings to register your app and send push notifications.
7073

7174
## Connect your app to the notification hub
72-
#### Create a new project
75+
76+
### Create a new project
77+
7378
1. In Visual Studio, create a new iOS project and select the **Single View App** template, and click **Next**
74-
79+
7580
![Visual Studio - Select Application Type][31]
7681

7782
2. Enter your App Name and Organization identifier, then hit **Next**, then **Create**
@@ -80,145 +85,147 @@ Your notification hub is now configured to work with APNS, and you have the conn
8085

8186
![Visual Studio- iOS App Config][32]
8287

83-
4. From the Solution view, double-click *Entitlements.plist* and ensure that "Enable Push Notifications" is checked.
88+
4. From the Solution view, double-click *Entitlements.plist* and ensure that **Enable Push Notifications**"** is checked.
8489

8590
![Visual Studio- iOS Entitlements Config][33]
8691

8792
5. 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.
8893

8994
6. Add a new file to your class, name it **Constants.cs** and add the following variables and replace the string literal placeholders with your *hub name* and the *DefaultListenSharedAccessSignature* noted earlier.
90-
95+
9196
```csharp
92-
// Azure app-specific connection string and hub path
93-
public const string ListenConnectionString = "<Azure connection string>";
94-
public const string NotificationHubName = "<Azure hub path>";
97+
// Azure app-specific connection string and hub path
98+
public const string ListenConnectionString = "<Azure DefaultListenSharedAccess Connection String>";
99+
public const string NotificationHubName = "<Azure Notification Hub Name>";
95100
```
96101

97102
7. In **AppDelegate.cs**, add the following using statement:
98-
103+
99104
```csharp
100-
using WindowsAzure.Messaging;
105+
using WindowsAzure.Messaging;
101106
```
102107

103108
8. Declare an instance of **SBNotificationHub**:
104-
109+
105110
```csharp
106-
private SBNotificationHub Hub { get; set; }
111+
private SBNotificationHub Hub { get; set; }
107112
```
108113

109-
9. In **AppDelegate.cs**, update **FinishedLaunching()** to match the following code:
110-
114+
9. In **AppDelegate.cs**, update **FinishedLaunching()** to match the following code:
115+
111116
```csharp
112-
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
117+
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
118+
{
119+
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
113120
{
114-
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
121+
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound,
122+
(granted, error) =>
115123
{
116-
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound,
117-
(granted, error) =>
118-
{
119-
if (granted)
120-
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
121-
});
122-
} else if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
123-
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes (
124-
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
125-
new NSSet ());
126-
127-
UIApplication.SharedApplication.RegisterUserNotificationSettings (pushSettings);
128-
UIApplication.SharedApplication.RegisterForRemoteNotifications ();
129-
} else {
130-
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
131-
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (notificationTypes);
132-
}
133-
134-
return true;
124+
if (granted)
125+
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
126+
});
127+
} else if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
128+
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes (
129+
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
130+
new NSSet ());
131+
132+
UIApplication.SharedApplication.RegisterUserNotificationSettings (pushSettings);
133+
UIApplication.SharedApplication.RegisterForRemoteNotifications ();
134+
} else {
135+
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
136+
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (notificationTypes);
135137
}
138+
139+
return true;
140+
}
136141
```
137142

138143
10. Override the **RegisteredForRemoteNotifications()** method in **AppDelegate.cs**:
139-
144+
140145
```csharp
141-
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
142-
{
143-
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
144-
145-
Hub.UnregisterAllAsync (deviceToken, (error) => {
146-
if (error != null)
147-
{
148-
Console.WriteLine("Error calling Unregister: {0}", error.ToString());
149-
return;
150-
}
151-
152-
NSSet tags = null; // create tags if you want
153-
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
154-
if (errorCallback != null)
155-
Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
156-
});
146+
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
147+
{
148+
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
149+
150+
Hub.UnregisterAllAsync (deviceToken, (error) => {
151+
if (error != null)
152+
{
153+
System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
154+
return;
155+
}
156+
157+
NSSet tags = null; // create tags if you want
158+
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
159+
if (errorCallback != null)
160+
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
157161
});
158-
}
162+
});
163+
}
159164
```
160165

161166
11. Override the **ReceivedRemoteNotification()** method in **AppDelegate.cs**:
162-
167+
163168
```csharp
164-
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
165-
{
166-
ProcessNotification(userInfo, false);
167-
}
169+
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
170+
{
171+
ProcessNotification(userInfo, false);
172+
}
168173
```
169174

170175
12. Create the following **ProcessNotification()** method in **AppDelegate.cs**:
171-
176+
172177
```csharp
173-
void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
178+
void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
179+
{
180+
// Check to see if the dictionary has the aps key. This is the notification payload you would have sent
181+
if (null != options && options.ContainsKey(new NSString("aps")))
174182
{
175-
// Check to see if the dictionary has the aps key. This is the notification payload you would have sent
176-
if (null != options && options.ContainsKey(new NSString("aps")))
183+
//Get the aps dictionary
184+
NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
185+
186+
string alert = string.Empty;
187+
188+
//Extract the alert text
189+
// NOTE: If you're using the simple alert by just specifying
190+
// " aps:{alert:"alert msg here"} ", this will work fine.
191+
// But if you're using a complex alert with Localization keys, etc.,
192+
// your "alert" object from the aps dictionary will be another NSDictionary.
193+
// Basically the JSON gets dumped right into a NSDictionary,
194+
// so keep that in mind.
195+
if (aps.ContainsKey(new NSString("alert")))
196+
alert = (aps [new NSString("alert")] as NSString).ToString();
197+
198+
//If this came from the ReceivedRemoteNotification while the app was running,
199+
// we of course need to manually process things like the sound, badge, and alert.
200+
if (!fromFinishedLaunching)
177201
{
178-
//Get the aps dictionary
179-
NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
180-
181-
string alert = string.Empty;
182-
183-
//Extract the alert text
184-
// NOTE: If you're using the simple alert by just specifying
185-
// " aps:{alert:"alert msg here"} ", this will work fine.
186-
// But if you're using a complex alert with Localization keys, etc.,
187-
// your "alert" object from the aps dictionary will be another NSDictionary.
188-
// Basically the JSON gets dumped right into a NSDictionary,
189-
// so keep that in mind.
190-
if (aps.ContainsKey(new NSString("alert")))
191-
alert = (aps [new NSString("alert")] as NSString).ToString();
192-
193-
//If this came from the ReceivedRemoteNotification while the app was running,
194-
// we of course need to manually process things like the sound, badge, and alert.
195-
if (!fromFinishedLaunching)
202+
//Manually show an alert
203+
if (!string.IsNullOrEmpty(alert))
196204
{
197-
//Manually show an alert
198-
if (!string.IsNullOrEmpty(alert))
199-
{
200-
UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
201-
avAlert.Show();
202-
}
205+
UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
206+
avAlert.Show();
203207
}
204208
}
205209
}
210+
}
206211
```
207-
> [!NOTE]
208-
> You can choose to override **FailedToRegisterForRemoteNotifications()** to handle situations such as no network connection. This is especially important where the user might start your application in offline mode (for example, Airplane) and you want to handle push messaging scenarios specific to your app.
209-
212+
213+
> [!NOTE]
214+
> You can choose to override **FailedToRegisterForRemoteNotifications()** to handle situations such as no network connection. This is especially important where the user might start your application in offline mode (for example, Airplane) and you want to handle push messaging scenarios specific to your app.
210215

211216
13. Run the app on your device.
212217

213218
## Send test push notifications
219+
214220
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.
215221

216222
![Azure portal - Test Send][30]
217223

218224
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.
219225

220226
## Next steps
221-
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:
227+
228+
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:
222229

223230
> [!div class="nextstepaction"]
224231
>[Push notifications to specific devices](notification-hubs-ios-xplat-segmented-apns-push-notification.md)
@@ -237,24 +244,12 @@ In this tutorial, you sent broadcast notifications to all your iOS devices regis
237244
[33]: ./media/partner-xamarin-notification-hubs-ios-get-started/notification-hub-entitlements-settings.png
238245

239246

240-
241247
<!-- URLs. -->
242-
[Submit an app page]: http://go.microsoft.com/fwlink/p/?LinkID=266582
243-
[My Applications]: http://go.microsoft.com/fwlink/p/?LinkId=262039
244-
[Live SDK for Windows]: http://go.microsoft.com/fwlink/p/?LinkId=262253
245-
[Windows Azure Messaging Framework]: http://go.microsoft.com/fwlink/?LinkID=799698&clcid=0x409
246-
[Get started with Mobile Services]: /develop/mobile/tutorials/get-started-xamarin-ios
247-
[Notification Hubs Guidance]: http://msdn.microsoft.com/library/jj927170.aspx
248-
[Notification Hubs How-To for iOS]: http://msdn.microsoft.com/library/jj927168.aspx
249248
[Install Xcode]: https://go.microsoft.com/fwLink/p/?LinkID=266532
250249
[iOS Provisioning Portal]: http://go.microsoft.com/fwlink/p/?LinkId=272456
251-
[Visual Studio for Mac]: https://www.visualstudio.com/vs/visual-studio-mac/
252-
[Use Notification Hubs to push notifications to users]: notification-hubs-aspnet-backend-ios-apple-apns-notification.md
253-
[Use Notification Hubs to send breaking news]: notification-hubs-windows-notification-dotnet-push-xplat-segmented-wns.md
250+
[Visual Studio for Mac]: https://visualstudio.microsoft.com/vs/mac/
254251
255252
[Local and Push Notification Programming Guide]:https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/HandlingRemoteNotifications.html#//apple_ref/doc/uid/TP40008194-CH6-SW1
256253
[Apple Push Notification Service]: http://go.microsoft.com/fwlink/p/?LinkId=272584
257254
258-
[Azure Mobile Services Component]: http://components.xamarin.com/view/azure-mobile-services/
259255
[GitHub]: https://github.com/xamarin/mobile-samples/tree/master/Azure/NotificationHubs
260-
[Azure Portal]: https://portal.azure.com

0 commit comments

Comments
 (0)