English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

iOS10Push Notification Development Tutorial

Although notifications are often overused, notifications are indeed an effective way to gain user attention and notify them of updates or actions needed. iOS 10With the new notifications, such as new messages, business information, and schedule changes. In this tutorial, I will show you how to use notifications in your iOS application and display iOS 10has introduced new features. Developing iOS 10For push notifications, you need the latest version of Xcode, Xcode 8beta versions, these are all available for download atDownloadpage.

You can go toGithub downloadThe entire project of this tutorial.

Start

Enabling push notifications in Xcode is easy, but you need to follow several steps.

Create a new project and give it a unique Bundle Identifier.

Once you have created the project, go to the Project Settings page and select the Capabilities pane. Enable push notifications as shown below.

Note: If you are an Apple paid developer member, you can see the push notification feature section.

Go to the Developer Account section, select Certificates, IDs, and Profiles from the left menu bar, and then select App IDs in the Identifiers pane. Find the name of the app you have created, select it in the service list. Note that there are two configurable states for push notifications.

Do not close this web page, you will be back soon.

Send notification

In this article, I will use Pusher to send push notifications. You can also use other solutions like Houston. Regardless of the method, to send a notification, you need a certificate.

To create a certificate, open Keychain Access, and select Keychain Access from the certificate authentication menu. -> Certificate Assistant -> Request a Certificate.

Fill out the form and click Continue. Make sure you save it to the disk.

Return to the developer account web page. You can generate a development (debug) certificate or a distribution certificate for your App IDs.

Then, in the right pane, click on the application at the bottom, and click Edit. In the push notification section, click Create Development (Debug) Certificate.

When needed, from Keychain, continue to upload the generated certificate request.

Now that you have created the certificate, you can download it. Open the downloaded file and install it.

Download and run Pusher. You need to fill in a push certificate at the top of this program. It is located in your keychain, and OS X will ask if you allow Pusher to access the certificate.

The second field requires a device token, which you will obtain in the next step.

Received notification

It's time to write code. The device receiving notifications must be registered with Apple Push Notification Service (APNS). You need to send a unique token when the app starts up.

Open AppDelegate.swift and add the following method.

Note: This code is based on Swift3The syntax may look different from what you have used before.

func registerPushNotifications() {
 DispatchQueue.main.async {
 let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
 UIApplication.shared().registerUserNotificationSettings(settings)
 }
}

I will explain later that in this setting, you will receive the specified notification types. Call this method in the file where the application starts.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]63;) -> Bool {
 registerPushNotifications()
 return true
}

At this point, the application will automatically pop up an Alert to ask the user whether they want to receive this notification.

Notifications must be registered to be sent, and whether to accept notifications requires user approval. The UIApplicationDelegate method handles the response.

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
 if notificationSettings.types != UIUserNotificationType() {
 application.registerForRemoteNotifications()
 }
}

Firstly, check the user's granted permissions, then call this method to register for remote notifications. When the request is completed, another delegate method will be called. This method responds with a device token, which you can print for debugging. This device token is required to identify the device when sending push notifications.

If an error occurs, call the following method.

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
 print("Registration failed!")
}

Note:It is important to call registerUserNotificationSettings when the application starts, because users can change the settings of permissions. Similarly, registerForRemoteNotifications is also very important, because in some scenarios, the device token can change and the notification will no longer be sent.

So far, this is enough to let you receive a simple notification.

Notification content

Through different notification content, there are different ways to make an App receive different types of notifications. This includes information notified to users by the application or information customized by the user.

Send notifications to the user using JSON format, which itself contains a dictionary corresponding to the aps key. In this second dictionary, you specify the content and key.

The most common ones are:

The notification message displayed to the user. It can be a simple string or a dictionary with keys and titles, body, etc.
The sound received when the notification is received. It can be a custom sound or a system sound.
The number of badges at the top right corner of the app icon. Set it to 0 to remove the badge.
Valid content. Use values1Send a silent notification to the user. It will not play any sound, or any badge settings, but when the notification is woken up, the app will communicate with the server.

A simple notification content for this tutorial:

{
 "aps": {
 "alert": {
 "title":"Hello! :)"
 "body":"App closed..."
 },
 "badge":1,
 "sound":"default"
 }
}

Application lifecycle

Copy the device token and paste it in the token section of Pusher, copy this JSON object in the payload section of Pusher.

Try sending the first notification. If the device's screen is locked, it will look like this, but nothing will happen when the user clicks on this notification view.

To accept notifications, you need to add a new method:

private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) {
 let aps = notification["aps"] as63; [String:AnyObject]
 let alert = aps63;["alert"] as63; [String:AnyObject]
 let title = alert63;["title"] as63; String
 let body = alert63;["body"] as63; String
 return (title63? "-", body63? "-")
}

This will return the received notification title and body, if the structure is the same.

func notificationReceived(notification: [NSObject:AnyObject]) {
 let viewController = window?.rootViewController
 let view = viewController as?ViewController
 ; #view63;.addNotification(
 title: getAlert(notification: notification).0,
 body: getAlert(notification: notification).1)
}

This method will add a line to the main view UITableView of the application (see the complete project code in ViewController).

I tested three casesPush notifications:

When the app is closed
If the user opens the application's notification, call the didFinishLaunchingWithOptions method to update, as follows:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]63;) -> Bool {
 // Override point for customization after application launch.
 application.applicationIconBadgeNumber = 0; // Clear badge when app launches
 // Check if launched from notification
 if let notification = launchOptions63;[UIApplicationLaunchOptionsRemoteNotificationKey] as63; [String: AnyObject] {
 ; #window63; #rootViewController63;.present(ViewController(), animated: true, completion: nil)
 notificationReceived(notification: notification)
 } else {
 registerPushNotifications()
 }
 return true
 }

If the user has already viewed this notification, the badge is cleared. Then, check if the application was opened from the icon or through the notification. In the first case, call the registerPushNotifications() method and continue with the previous process. If the app was run by opening the notification, call the custom notificationReceived method to add a line.

When the app is running in the foreground
If the user is using the application, this means the application is in the foreground, and the method to accept notifications is as follows. Add the handling of tableView to this notification method:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
 notificationReceived(notification: userInfo)
}

Note: In this case, notifications will not make a sound.

When the app is running in the background
In this case, I added a method to clear the badge number. The handling of notifications is the same as the handling of the application in the foreground.

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

Finally, there are three lines in this list from the notification content.

Finally

With iOS 10notification, developers have more interesting opportunities and unprecedented interaction permissions than before. I hope this tutorial about how to use notifications can help you better understand how notifications work.

This article has been organized into 'iOS Push Tutorial', welcome to learn and read.

That's all for this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support and cheer for the tutorial.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#w3If you find any infringing content, please report by email to codebox.com (replace # with @ when sending an email), and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.