You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: articles/notification-hubs/notification-hubs-ios-push-notifications-swift-apps-get-started.md
+64-30Lines changed: 64 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
---
1
+
---
2
2
title: Send push notifications to Swift iOS apps that use Azure Notification Hubs | Microsoft Docs
3
3
description: Learn how to push notifications to Swift iOS apps that use Azure Notification Hubs.
4
4
services: notification-hubs
@@ -38,6 +38,8 @@ This tutorial takes you through the following steps:
38
38
> * Connect your iOS app to a notification hub.
39
39
> * Test the solution.
40
40
41
+
The complete code for this tutorial can be found [on GitHub](https://github.com/xamcat/mobcat-samples/tree/master/notification_hub_rest).
42
+
41
43
## Prerequisites
42
44
43
45
To follow along, you need:
@@ -110,18 +112,18 @@ In this section, you'll build the iOS app that will connect to the notification
110
112
111
113
1. Find **Identity** and then set the **Bundle Identifier** value so that it matches `com.<organization>.PushDemo`, which is the value used for the **App ID** from a previous step.
112
114
113
-
1. Find **Signing**, and then select the appropriate **Team** for your **Apple Developer Account**. The **Team** value should match the one under which you created your certificates and profiles.
115
+
1. Find **Signing & Capabilities**, and then select the appropriate **Team** for your **Apple Developer Account**. The **Team** value should match the one under which you created your certificates and profiles.
114
116
115
-
1. Xcode should automatically pull down the appropriate **Provisioning Profile** value based on the **Bundle Identifier**. If you don't see the new **Provisioning Profile** value, try refreshing the profiles for the **Signing Identity** by selecting **Xcode** > **Preferences** > **Account**> **View Details**. Select **Signing Identity**, and then select the **Refresh** button in the bottom right to download the profiles.
117
+
1. Xcode should automatically pull down the appropriate **Provisioning Profile** value based on the **Bundle Identifier**. If you don't see the new **Provisioning Profile** value, try refreshing the profiles for the **Signing Identity** by selecting **Xcode** > **Preferences** > **Account** then select the **Download Manual Profiles** button to download the profiles.
116
118
117
-
1.Select the **Capabilities** taband ensure that **push notifications** are enabled.
119
+
1.Still on the **Signing & Capabilities** tab, click the **+ Capability** button and double tap on **Push Notifications** from the list to ensure **Push Notifications** are enabled.
118
120
119
121
1. Open your **AppDelegate.swift** file to implement the **UNUserNotificationCenterDelegate** protocol and add the following code to the top of the class:
@@ -130,13 +132,12 @@ In this section, you'll build the iOS app that will connect to the notification
130
132
var notificationHubKeyName : String?
131
133
var notificationHubKey : String?
132
134
let tags = ["12345"]
133
-
let genericTemplate =PushTemplate(withBody: "{\"aps\":{\"alert\":\"$(message)\"}}")
134
-
135
+
135
136
...
136
137
}
137
138
```
138
139
139
-
You'll use these members later. Specifically, you'll use the **tags**and **genericTemplate** members as part of the registration. For more information on tags, see [Tags for registrations](notification-hubs-tags-segment-push-message.md) and [Template registrations](notification-hubs-templates-cross-platform-push-messages.md).
140
+
You'll use these members later. Specifically, you'll use the **tags**member as part of the registration using a **custom template**. For more information on tags, see [Tags for registrations](notification-hubs-tags-segment-push-message.md) and [Template registrations](notification-hubs-templates-cross-platform-push-messages.md).
140
141
141
142
1. In the same file, add the following code to the **didFinishLaunchingWithOptions** function:
142
143
@@ -182,7 +183,8 @@ In this section, you'll build the iOS app that will connect to the notification
182
183
funcshowAlert(withText text :String) {
183
184
let alertController =UIAlertController(title: "PushDemo", message: text, preferredStyle: UIAlertControllerStyle.alert)
@@ -208,6 +210,11 @@ In this section, you'll build the iOS app that will connect to the notification
208
210
209
211
1. Add print statements to the bottom of the **didRegisterForRemoteNotificationsWithDeviceToken** function to verify that **installationId** and **pushChannel** are being assigned values.
210
212
213
+
```swift
214
+
print(installationId)
215
+
print(pushChannel)
216
+
```
217
+
211
218
1. Create the **Models**, **Services**, and **Utilities** folders for the foundational components you'll be adding to the project later.
212
219
213
220
1. Check that the project builds and runs on a physical device. Push notifications can't be tested by using the simulator.
@@ -307,9 +314,9 @@ To add and configure the bridging header:
307
314
#endif/* BridgingHeader_h */
308
315
```
309
316
310
-
1. Update the Target's **Build Settings** to reference the bridging header:
317
+
1. Update the Target’s **Build Settings** to reference the bridging header:
311
318
312
-
1. Open the **Building Settings**tab and scroll down to the **Swift Compiler** section.
319
+
1. Tap on the **PushDemo**project and scroll down to the **Swift Compiler** section.
313
320
314
321
1. Ensure that the **Install Objective-C Compatibility Header** option isset to **Yes**.
315
322
@@ -388,11 +395,25 @@ To add and configure the bridging header:
388
395
389
396
The [Azure Storage iOS SDK](https://github.com/Azure/azure-storage-ios/blob/master/Lib/Azure%20Storage%20Client%20Library/Azure%20Storage%20Client%20Library/AZSUtil.m) is an excellent example of how to approach these operations in Objective-C. Further information on Azure Service Bus SAS tokens can be found in the [Azure Service Bus documentation](../service-bus-messaging/service-bus-sas.md).
390
397
398
+
1. In **AppDelegate.swift**, add the following code to the *didRegisterForRemoteNotificationsWithDeviceToken* function to verify that the **TokenUtility.getSasToken**is generating a valid token
399
+
400
+
```swift
401
+
let baseAddress ="https://<notificaitonHubNamespace>.servicebus.windows.net/<notifiationHubName>"
402
+
403
+
let tokenData = TokenUtility.getSasToken(forResourceUrl: baseAddress,
404
+
withKeyName: self.notificationHubKeyName!,
405
+
andKey: self.notificationHubKey!)
406
+
407
+
print(tokenData.token)
408
+
```
409
+
410
+
Be sure to replace the placeholder values in the **baseAddress** string with your own
411
+
391
412
### Verify the SAS token
392
413
393
414
Before you implement the installation service in the client, check that our app is correctly generating the SAS token by using your HTTP utility of choice. For the purposes of this tutorial, our tool of choice will be **Postman**.
394
415
395
-
Use an appropriately placed print statement or breakpoint to note the **installationId** and the**token** values being generated by the app.
416
+
Make a note of the **installationId** and **token** values being generated by the app.
396
417
397
418
Follow these steps to call the **installations** API:
398
419
@@ -451,7 +472,8 @@ class NotificationRegistrationService {
451
472
privatelet keyName : String
452
473
privatelet key : String
453
474
privatevar tokenData : TokenData?=nil
454
-
475
+
privatevar tokenExpiryDate : Date?=nil
476
+
455
477
init(withInstallationIdinstallationId : String,
456
478
andPushChannelpushChannel : String,
457
479
andHubNamespacehubNamespace : String,
@@ -466,58 +488,67 @@ class NotificationRegistrationService {
@@ -548,10 +579,11 @@ Finally, **encodeToJson** converts the respective model objects into JSON for us
548
579
549
580
The last step is updating **AppDelegate** to use **NotificationRegistrationService** to register with our **NotificationHub**.
550
581
551
-
1. Open **AppDelegate.swift** and add a class-level variable to store a reference to the **NotificationRegistrationService**:
582
+
1. Open **AppDelegate.swift** and add class-level variables to store a reference to the **NoficiationRegistrationService** and the generic **PushTemplate**:
552
583
553
584
```swift
554
585
var registrationService : NotificationRegistrationService?
586
+
let genericTemplate =PushTemplate(withBody: "{\"aps\":{\"alert\":\"$(message)\"}}")
555
587
```
556
588
557
589
1. In the same file, update the **didRegisterForRemoteNotificationsWithDeviceToken** function to initialize the **NotificationRegistrationService** with the requisite parameters, and then call the **register** function.
@@ -614,6 +646,8 @@ You can now make the same request as you did previously by using **Postman** for
614
646
}
615
647
```
616
648
649
+
If your previous **SAS token** has expired, you can add a **breakpoint** to **line 24** of the **TokenUtility**class to get a new **SAS token** and update the **Authorization** header with that new value.
650
+
617
651
### Send a test notification (Azure portal)
618
652
619
653
The quickest way to test that you can now receive notifications is to browse to the notification hub in the Azure portal:
@@ -688,7 +722,7 @@ You can send notifications via the [REST API](/rest/api/notificationhubs/) by us
688
722
689
723
1. Select the **Send** button.
690
724
691
-
You should get a success status code and receive the notification on the client device.
725
+
You should get a **201 Created**success status code and receive the notification on the client device..
692
726
693
727
## Next steps
694
728
You now have a basic iOS Swift app connected to a notification hub via the [REST API](/rest/api/notificationhubs/) and can send and receive notifications. For more information, see the following articles:
0 commit comments