How to Use Push Notifications in iOS 10

How to Use Push Notifications in iOS 10

Introduction

Although often overused, push notifications are an effective way to attract users' attention, such as notifying them to update software or take corresponding actions, etc. Currently, the new iOS 10 system also provides new support for push notifications, such as new messages, offers, and schedule changes.

In this tutorial, you will learn how to use push notifications in your iOS applications, while also showing you some of the new features of iOS 10. In order to develop iOS 10 push notifications, you need to use the Xcode 8 Beta version.

Getting Started

Enabling push notifications in Xcode is easy. Follow these steps:

1. Launch Xcode and create a new project, giving it a unique name and a corresponding bundle identifier.

2. After creating the project, go to the [Project Settings] interface and select the [Capabilities] tab. Then, enable the push notification function, as shown in the figure below.

[Note] If you are a paid member of the Apple Developer Program, you will only see the [Push Notifications] function item.

Next, go to the Developer Account section and check the changes that Xcode automatically made. Select Certificates, IDs & Profiles from the menu on the left, then select App IDs in the Identifiers section. Find the name of the application you just created and select it so that the corresponding service list is displayed.

【Note】There are two configurable states near 【Push Notifications】.

Do not close this screen yet, you will return to it shortly.

Send notification

In this article, I will use Pusher technology (https://github.com/noodlewerk/NWPusher/releases/tag/0.7.0) to send push notifications. In fact, you can also use other solutions, such as Houston technology (https://github.com/nomad/houston). No matter which method you take, you need to use certificates to send notifications.

To create a certificate, you need to open Keychain Access and select the "Keychain Access -> Certificate Assistant -> Request a Certificate from a Certificate Authority" menu item.

Fill in the form as shown below and click the [Continue] button. Please make sure your selections are saved to disk.

Now, return to the [Developer Account] screen, where you can generate a certificate for development or deployment in [App IDs]. After selecting the corresponding application, click the [Edit] command at the bottom. Then, in the [Push Notifications] section, click [Create Certificate for development].

If necessary, you need to upload the certificate request generated by the keychain, and then click the [Continue] button. Please refer to the figure below.

You have now created the certificate and can download it. To install it, open the downloaded file.

Now you can download and run Pusher.

【Note】In the combo box at the top of the window, you are asked to select a Push Certificate. Because it is in your keychain, OS X will ask whether to allow access to the certificate.

The second field in the image above (note the grayed-out drop-down list control) requires you to enter a device token, which you will get in the next step.

Get Notifications

From now on, you need to write code. The device that will receive notifications must be registered with the Apple Push Notification Service (APNS). To do this, you need to send a unique token that is generated when the application is launched.

Next, open the file AppDelegate.swift and add the following method.

【Note】This code includes the latest Swift 3.0 syntax; therefore, some syntax may be different from the 2.0 format you are familiar with.

  1. func registerPushNotifications() {
  2.  
  3. DispatchQueue.main.async {
  4.  
  5. let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
  6.  
  7. UIApplication.shared().registerUserNotificationSettings(settings)
  8.  
  9. }
  10.  
  11. }

In the settings here, you need to specify the types that your application will receive (described later). This method is called when the application starts.

  1. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  2.  
  3. registerPushNotifications()
  4.  
  5. return   true  
  6.  
  7. }

At this point, the application will automatically display a pop-up window asking the user to pass the corresponding permission to send notifications.

Only when the user agrees to it can the notification be registered and sent. Among them, the UIApplicationDelegate method is responsible for handling the response issue.

  1. func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
  2.  
  3. if notificationSettings.types != UIUserNotificationType() {
  4.  
  5. application.registerForRemoteNotifications()
  6.  
  7. }
  8.  
  9. }

In the above code, we first check if the user has granted permission, and then call a method to register for remote notifications. When the request is completed, the latter will call another delegate method. Notice that the response message contains a device token (you can output this during debugging). You will need this token when sending push notifications to identify the device.

  1. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  2.  
  3. let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes)
  4.  
  5. var token = ""  
  6.  
  7. for i in 0..<deviceToken. count {
  8.  
  9. token += String(format: "%02.2hhx" , arguments: [chars[i]])
  10.  
  11. }
  12.  
  13. print( "Registration succeeded!" )
  14.  
  15. print( "Token: " , token)
  16.  
  17. }

If an error occurs, the following method is called.

  1. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
  2.  
  3. print( "Registration failed!" )
  4.  
  5. }

Note: It is important to call the registerUserNotificationSettings method when launching the application because it is possible for the user to change the permissions of their settings. In addition, the RegisterForRemoteNotifications method is also important because there are cases where the device token can change and notifications will no longer be sent.

So far, your setup is sufficient to receive a simple notification.

Notification Payload

There are several different ways an application can receive notifications. This is simply specified in the payload portion of the notification, which contains how the application will notify the user and any custom data you can send with the notification.

The notification that is sent to the user is actually a JSON dictionary, which itself contains a dictionary with the key aps. In this second dictionary, you can specify key/value pairs for the payload part.

The most common data are:

The notification message to display to the user. This can be a simple string or a dictionary with keys like title, body, etc.

The sound that will play when the device receives a notification. It can be a custom sound from the application or a system sound.

A number that the app will use as a badge near its icon. Setting this to 0 will remove the badge.

content-available: A value of 1 sends a silent notification to the user. In this case, no sound is played or any badge number is set, but it wakes up the app so that it can communicate with the server.

The notification content that will be used in the rest of this tutorial is as follows:

  1. {
  2.  
  3. "aps" : {
  4.  
  5. "alert" : {
  6.  
  7. "title" : "Hello! :)" ,
  8.  
  9. "body" : "App closed..."  
  10.  
  11. },
  12.  
  13. "badge" :1,
  14.  
  15. "sound" : "default"  
  16.  
  17. }
  18.  
  19. }

Application Lifecycle

Copy the device token displayed in the Xcode console to Pusher. Then, copy the JSON object from the previous section to the payload text field (the text box at the bottom of the image below).

Now you can try to push the first notification. If the device's screen is locked, it should look like the following. However, when the user selects the view, nothing happens.

To handle notifications, you need to add a few more new methods. The relevant code is as follows:

  1. private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) {
  2.  
  3. let aps = notification[ "aps" ] as ? [String:AnyObject]
  4.  
  5. let alert = aps?[ "alert" ] as ? [String:AnyObject]
  6.  
  7. let title = alert?[ "title" ] as ? String
  8.  
  9. let body = alert?[ "body" ] as ? String
  10.  
  11. return (title ?? "-" , body ?? "-" )
  12.  
  13. }

If the structure is the same, this code will return the title and body content of the received notification.

  1. func notificationReceived(notification: [NSObject:AnyObject]) {
  2.  
  3. let viewController = window?.rootViewController
  4.  
  5. let view = viewController as ? ViewController
  6.  
  7. view ?.addNotification(
  8.  
  9. title: getAlert(notification: notification).0,
  10.  
  11. body: getAlert(notification: notification).1)
  12.  
  13. }

This method adds a new row to the UITableView in the app’s main view (see the project for the complete ViewController code).

I tested the usage of push notifications in three scenarios.

When the application is closed

If the user opens the app from the notification, the modified didFinishLaunchingWithOptions method is called as shown below:

  1. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  2.  
  3. // Override point for customization after application launch.
  4.  
  5. application.applicationIconBadgeNumber = 0; // Clear badge when app launches
  6.  
  7. // Check if launched from notification
  8.  
  9. if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as ? [String: AnyObject] {
  10.  
  11. window?.rootViewController?.present(ViewController(), animated: true , completion: nil)
  12.  
  13. notificationReceived(notification: notification)
  14.  
  15. } else {
  16.  
  17. registerPushNotifications()
  18.  
  19. }
  20.  
  21. return   true  
  22.  
  23. }

In the above code, the badge is cleared assuming that the user has seen the notification. Then, it is checked whether the application was opened via the icon or using the notification method. In the first case, the registerPushNotifications() method is called and the previous flow continues. If the application is run via notifications, the custom notificationReceived method is called and a new row is added.

When the app is in the foreground

If the user is using the application, that is, the application is in the foreground, you can use the following method to handle the notification. This method will add the notification to the tableView view:

  1. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
  2.  
  3. notificationReceived(notification: userInfo)
  4.  
  5. }

【Note】In this case, the notification will not play sound.

When the app is in the background

In this case I added a method to clear the badge number. The notification is handled the same way as when the app is in the foreground.

  1. func applicationWillEnterForeground(_ application: UIApplication) {
  2.  
  3. application.applicationIconBadgeNumber = 0; // Clear badge when app is   or resumed
  4.  
  5. }

Finally, the table will display three rows corresponding to all notification information; please refer to the figure below.

summary

Push notification support in iOS 10 is another very interesting opportunity for programmers, as it can provide different levels of interaction that were simply not available in previous versions. In the end, I hope this article can provide you with a good reference for using push notifications in your own applications.

<<:  How to implement sharing function in Android

>>:  React Native Introduction and Getting Started

Recommend

Zheng Duoyan [Fat Burning] Series

Zheng Duoyan's [Burning Fat] series resource ...

The more you eat, the whiter your skin becomes?! The truth is...

Whitening - an eternal topic in the skin care ind...

High-quality case studies on information flow delivery in the automotive industry

It’s the end of the year and it’s the crazy car b...

Apple to try adding mental health features to iPhone

Apple is working on a series of new programs to h...

Where the Heart “Sounds” – Exploring the Beautiful Sounds of the Heart

Author: Chen Bingwei, deputy chief physician of T...

Don't eat it! It has 3,000 to 6,000 parasites in its body.

As the temperature rises In parks, wetlands, pond...

The most comprehensive network operation solution analysis!

1. Competitive product analysis 1. Choose competi...

Work hard to build a world-class science and technology power

General Secretary Xi Jinping pointed out that my ...