-->![Mac Mac](/uploads/1/2/6/3/126355224/416973527.jpg)
![Ios Ios](/uploads/1/2/6/3/126355224/212770629.jpg)
This tutorial describes how to use Azure Notification Hubs to send push notifications to an iOS application using REST APIs.
Apple Purges App Store Apps & Encourages Use of Web Apps. Recent activities by Apple provide signals businesses should consider using Progressive Web Applications instead of native apps for iOS 13. These actions include purging existing apps from the store and blocking access to other, corporate applications. You can keep your phone in your pocket and still know what’s going on. Stay up-to-date on your incoming WhatsApp messages, know when someone's calling you, or read any of the other notifications from any app on your iPhone. You can mute apps so you won't receive notifications from apps that are also running on your Mac.
This tutorial covers the following steps:
- Create a sample iOS app.
- Connect your iOS app to Azure Notification Hubs.
- Send test push notifications.
- Verify that your app receives notifications.
The complete code for this tutorial can be downloaded from GitHub.
Prerequisites
To complete this tutorial, you need the following prerequisites:
- A Mac running Xcode, along with a valid developer certificate installed into your Keychain.
- An iPhone or iPad running iOS version 10 or later.
- Your physical device registered in the Apple Portal and associated with your certificate.
Before you proceed, be sure to go through the previous tutorial on getting started with Azure Notification Hubs for iOS apps to set up and configure push credentials in your notification hub. Even if you have no prior experience with iOS development, you should be able to follow these steps.
![Mac Mac](/uploads/1/2/6/3/126355224/416973527.jpg)
Note
Because of configuration requirements for push notifications, you must deploy and test push notifications on a physical iOS device (iPhone or iPad), instead of the iOS emulator.
In the following sections, you build an iOS app that connects to the notification hub.
Create an iOS project
Apps Use Notifications Mac Ios 8
- In Xcode, create a new iOS project and select the Single View Application template.
- When setting the options for the new project:
- Specify the Product Name (PushDemo) and Organization Identifier (
com.<organization>
) that you used when you set the Bundle Identifier in the Apple Developer Portal. - Choose the Team for which the App ID was set up.
- Set the language to Swift.
- Select Next.
- Specify the Product Name (PushDemo) and Organization Identifier (
- Create a new folder called SupportingFiles.
- Create a new p-list file called devsettings.plist in the SupportingFiles folder. Be sure to add this folder to your gitignore file so it isn't committed when working with a git repo. In a production app, you might be conditionally setting these secrets as part of an automated build process. These settings are not covered in this tutorial.
- Update devsettings.plist to include the following configuration entries by using your own values from the notification hub that you provisioned:
Key Type Value notificationHubKey String <hubKey>
notificationHubKeyName String <hubKeyName>
notificationHubName String <hubName>
notificationHubNamespace String <hubNamespace>
You can find the required values by navigating to the notification hub resource in the Azure portal. In particular, the notificationHubName and notificationHubNamespace values are in the upper-right corner of the Essentials summary within the Overview page.You can also find the notificationHubKeyName and notificationHubKey values by navigating to Access Policies and selecting the respective Access Policy, such as DefaultFullSharedAccessSignature. After that, copy from the Primary Connection String the value prefixed withSharedAccessKeyName=
for notificationHubKeyName, and the value prefixed withSharedAccessKey=
for the notificationHubKey. The connection string should be in the following format: https://giftenergy304.weebly.com/indian-penal-code-in-hindi-free-download.html.For simplicity, specify DefaultFullSharedAccessSignature, so that you can use the token to send notifications. In practice, the DefaultListenSharedAccessSignature is a better choice for situations in which you only want to receive notifications. - Under Project Navigator, select the Project Name and then select the General tab.
- 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. - 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.
- Xcode should automatically download 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, then Preferences, Account, and then select the Download Manual Profiles button to download the profiles.
- 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.
- Open your AppDelegate.swift file to implement the UNUserNotificationCenterDelegate protocol and add the following code to the top of the class: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 and Template registrations.
- In the same file, add the following code to the didFinishLaunchingWithOptions function:This code retrieves the settings from devsettings.plist, sets the AppDelegate class as the UNUserNotificationCenter delegate, requests authorization for push notifications, and then calls registerForRemoteNotifications.For simplicity, the code only supports iOS 10 and later. You can add support for previous iOS versions by conditionally using the respective APIs and approaches, as you would normally do.
- In the same file, add the following code:This code uses the installationId and pushChannel values to register with the notification hub. In this case, you're using UIDevice.current.identifierForVendor to provide a unique value to identify the device and then formatting the deviceToken to provide the desired pushChannel value. The showAlert function exists simply to display some message text for demonstration purposes.
- Still in the AppDelegate.swift file, add the willPresent and didReceive functions to UNUserNotificationCenterDelegate. These functions display an alert when they're notified that an app is running in either the foreground or the background.
- Add
print
statements to the bottom of the didRegisterForRemoteNotificationsWithDeviceToken function to verify that installationId and pushChannel are being assigned values: - Create the Models, Services, and Utilities folders for the foundational components you'll be adding to the project later.
- Check that the project builds and runs on a physical device. Push notifications cannot be tested by using the simulator.
Create models
In this step, you create a set of models to represent the Notification Hubs REST API payloads, and to store the required shared access signature (SAS) token data.
- Add a new Swift file called PushTemplate.swift to the Models folder. This model defines a structure that represents the BODY of an individual template as part of the DeviceInstallation payload.
- Add a new Swift file called DeviceInstallation.swift to the Models folder. This file defines a structure that represents the payload for creating or updating a Device Installation. Add the following code to the file:
- Add a new Swift file called TokenData.swift to the Models folder. This model is used to store a SAS token along with its expiration. Add the following code to the file:
Generate a SAS token
Notification Hubs uses the same security infrastructure as Azure Service Bus. To call the REST API, programmatically generate a SAS token that can be used in the Authorization header of the request.
The resulting token will be in the following format:
The process itself involves the same six steps:
- Compute the expiry in UNIX Epoch time format, which means the number of seconds elapsed since midnight Universal Coordinated Time, January 1, 1970.
- Format the ResourceUrl that represents the resource you're trying to access so it's percent-encoded and lowercase. The ResourceUrl has the format
https://<namespace>.servicebus.windows.net/<hubName>
. - Prepare the StringToSign, which is formatted as
<UrlEncodedResourceUrl>n<ExpiryEpoch>
. - Compute and Base64-encode the Signature by using the HMAC-SHA256 hash of the StringToSign value. The hash value is used with the Key part of the Connection String for the respective Authorization Rule.
- Format the Base64-encoded Signature so it's percent encoded.
- Construct the token in the expected format by using the UrlEncodedSignature, ExpiryEpoch, KeyName, and UrlEncodedResourceUrl values.
See the Azure Service Bus documentation for a more complete overview of shared access signatures, and how AzureService Bus and Notification Hubs use it.
For the purposes of this Swift example, you use the Apple open-source CommonCrypto library to help with the hashing of the signature. As it's a C library, it is not accessible in Swift out of the box. You can make the library available by using a bridging header. Best webcam for mac mini.
To add and configure the bridging header:
- In Xcode, select File, then New, then File, and then select Header File. Name the header file BridgingHeader.h.
- Edit the file to import CommonHMAC.h: How to download text from etsy to mac.
- Update the target Build Settings to reference the bridging header:
- Select the PushDemo project and scroll down to the Swift Compiler section.
- Ensure that the Install Objective-C Compatibility Header option is set to Yes.
- Enter the file path
<ProjectName>/BridgingHeader.h
in the Objective-C bridging Header option. This is the file path to the bridging header.
If you can't find these options, ensure that you have the All view selected, rather than Basic or Customized.There are many third-party open-source wrapper libraries available that might make using CommonCrypto a bit easier. However, discussion of these libraries is beyond the scope of this article. - https://goldengenerous615.weebly.com/stop-motion-animation-mac-app.html. Add a new Swift file named TokenUtility.swift within the Utilities folder, and add the following code:This utility encapsulates the logic responsible for generating the SAS token.As outlined previously, the getSasToken function orchestrates the high-level steps required to prepare the token. The function will be called by the installation service later in this tutorial.The other two functions are called by the getSasToken function: sha256HMac for computing the signature, and urlEncodedString for encoding the associated URL string. The urlEncodedString function is required, as it is not possible to achieve the required output by using the built-in addingPercentEncoding function.The Azure Storage iOS SDK 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.
- In AppDelegate.swift, add the following code to the
didRegisterForRemoteNotificationsWithDeviceToken
function to verify that the TokenUtility.getSasToken is generating a valid tokenBe sure to replace the placeholders in the baseAddress string with your own values.
Verify the SAS token
Before you implement the installation service in the client, check that your app is correctly generating the SAS token by using an HTTP utility. For the purposes of this tutorial, our tool of choice is Postman.
Make a note of the installationId and token values generated by the app.
Follow these steps to call the installations API:
- In Postman, open a new tab.
- Set the request to GET and specify the following address:
- Configure the request headers as follows:
Key Value Content-Type application/json Authorization <sasToken> x-ms-version 2015-01 - Select the Code button that appears on the upper-right under the Save button. The request should look similar to the following example:
- Select the Send https://oramaskyey814.weebly.com/ansi-code-free-download-pdf.html. button.
No registration exists for the specified installationId at this point. The verification should result in a '404 Not Found' response rather than a '401 Unauthorized' response. This result should confirm that the SAS token has been accepted.
Use Iphone Apps On Mac
Implement the installation service class
Next, implement a basic wrapper around the Installations REST API.
Add a new Swift file named NotificationRegistrationService.swift underthe Services folder, and then add the following code to this file:
The requisite details are provided as part of initialization. Tags and templates are optionally passed into the register function to form part of the Device Installation JSON payload.
The register function calls the other private functions to prepare the request. After a response is received, the completion is called and indicates whether the registration was successful.
The request endpoint is constructed by the getBaseAddress function. The construction uses the notification hub parameters namespace and name that were provided during initialization.
The getSasToken function checks whether the currently stored token is valid. If the token isn't valid, the function calls TokenUtility to generate a new token and then stores it before returning a value.
Finally, encodeToJson converts the respective model objects into JSON for use as part of the request body.
Invoke the Notification Hubs REST API
The last step is updating AppDelegate to use NotificationRegistrationService to register with the NotificationHub.
- Open AppDelegate.swift and add class-level variables to store a reference to the NoficiationRegistrationService and the generic PushTemplate:
- In the same file, update the didRegisterForRemoteNotificationsWithDeviceToken function to initialize the NotificationRegistrationService with the requisite parameters, and then call the register function.For simplicity, the code uses
print
statements to update the output window with the result of the register operation. - Build and run the app on a physical device. You should see Registered in the output window.
Test the solution
At this point the app is registered with NotificationHub and can receive push notifications. In Xcode, stop the debugger and close the app if it's currently running. Next, check that the Device Installation details appear as expected and that the app can now receive push notifications.
Verify the device installation
You can now make the same request as you did previously, by using Postman for verifying the SAS token. Assuming that the SAS token hasn't expired, the response should now include the installation details you provided, such as the templates andtags.
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.
![Ios Ios](/uploads/1/2/6/3/126355224/212770629.jpg)
Send a test notification (Azure portal)
The quickest way to test that you can now receive notifications is to browse to the notification hub in the Azure portal:
- In the Azure portal, browse to the Overview tab on your notification hub.
- Select Test Send, which is above the Essentials summary in the upper-left of the portal window:
- Choose Custom Template from the Platforms list.
- Enter 12345 for the Send to Tag Expression. You had previously specified this tag in your installation.
- Optionally, edit the message in the JSON payload:
- Select Send. The portal should indicate whether the notification was successfully sent to the device:Assuming that the app isn't running in the foreground, you should also see a notification in the Notification Center on your device. Tapping the notification should open the app and show the alert.
Send a test notification (mail carrier)
You can send notifications via the REST API using Postman, which may be a more convenient way to test.
- Open a new tab in Postman.
- Set the request to POST, and enter the following address:
- Configure the request headers as follows:
Key Value Content-Type application/json;charset=utf-8 Authorization <sasToken> ServiceBusNotification-Format template Tags '12345' - Configure the request BODY to use RAW - JSON (application.json) with the following JSON payload:
- Select the Code button, which is under the Save button on the upper-right of the window. The request should look similar to the following example:
- Select the Send button.
You should get a 201 Created success status code and receive the notification on the client device.
Next steps
You now have a basic iOS Swift app connected to a notification hub via the Notification Hubs REST API, and can send and receive notifications. To learn more about how to send notifications to specific devices, advance to the following tutorial:
For more information, see the following articles: