IOS 10 push notification development tutorial and iOS 10 push notification tutorial

Source: Internet
Author: User

IOS 10 push notification development tutorial and iOS 10 push notification tutorial

Although notifications are often used excessively, notifications are indeed an effective way to get user attention and notify them of updates or actions they need. There are new notifications for iOS 10, such as new messages, business information, and schedule changes. In this tutorial, I will show you how to use notifications in your iOS app, and show that iOS 10 introduces new features. To develop iOS 10 push notifications, you need the latest version of Xcode and Xcode 8 Beta versions. These are currently downloadable on the download page.

You can go to Github to download the entire project of this tutorial.

Start

It is easy to enable push notification in Xcode, but you need several steps.

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

When you have created a project, go to the Project Settings page and select the Capabilities column. Open the push notification, as shown below.

Note: If you are a paid developer of apple, you can see the push notification function column.

Go to the Developer Account column, select certificate, IDs, and description file from the menu bar on the left, and then select App IDs in the Identifiers column. Find the name of the created App and select it in the service list. Note that two push notifications can be configured.

Don't close this webpage. You will be back soon.

Send notification

In this article, I will use Pusher to send push notifications. You can also use other solutions such as Houston. Either way, you need a certificate to send a notification.

Create a Certificate, open Keychain Access, and select Keychain Access> Certificate Assistant> Request a Certificate from the Certificate authentication menu.

Enter the form and click Continue. Make sure you choose to save it to the disk.

Return to the webpage of the developer account. You can generate a development (debugging) Certificate or publish a certificate for your App IDs.

Click Edit at the bottom of the application on the right. In the push notification section, click Create Development (debugging) certificate.

If necessary, upload the certificate generation request from the Keychain.

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

Download and run Pusher. Enter a pushed certificate at the top of the program. For it located in your key chain, OS X will ask if Pusher is allowed to access the certificate.

The second field requires device token and you will hit it in the next step.

Receive notification

It's time to repeat the code. The device that receives the notification must register with the APNS service ). When the application starts, you need to send a unique token.

Open AppDelegate. swift and add the following method.

Note: This Code is based on Swift3.0. The syntax may seem different from the one you 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 you will receive the specified notification type in this setting. Call this method in the file started by the application.

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

At this time, the application will automatically pop up an Alert and ask the user if they want to receive the notification.

A notification must be registered before it can be sent. User approval is required if the notification is accepted. The UIApplicationDelegate method processes the response.

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

First check the permissions granted by the user, and then call this method to register remote notifications. When the request is complete, the latter will call another proxy method. The response to this method contains a device token, which can be printed for debugging. This device token is required to send a push notification to identify the device.

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 the user can change the permission settings. Likewise, registerForRemoteNotifications are important, because in some scenarios, the device token can be changed, so the notification will not be sent.

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

Notification content

Different notification content can be used to enable an App to receive different types of notifications, including information that the App notifies users or user-defined information.

Send notifications to users in JSON format. This format contains a dictionary and corresponds to the aps key. In the second dictionary, you specify the loaded content and key.

The most common is:

Notification message displayed to the user. This is a simple string, or a dictionary key is the same as the title, body, and so on.
The voice of the notification. It can be a custom sound or a system sound.
Number of badge in the upper-right corner of the application icon. Set it to 0 to remove the badge.
Valid content. Use value 1 to send a silent notification to the user. It does not play any sound or badge settings, but when the notification is awakened, the application will communicate with the server.

A simple notification content in this tutorial:

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

Application Lifecycle

Copy the device token and paste it in the Pusher token section. Copy the JSON object in the payload section of Pusherd.

Try to send the first notification. If the screen of the device is locked, it will look like this, but nothing will happen, when the user clicks this Notification View.

To receive the notification, you need to add a new method:

private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) { let aps = notification["aps"] as? [String:AnyObject] let alert = aps?["alert"] as? [String:AnyObject] let title = alert?["title"] as? String let body = alert?["body"] as? String return (title ?? "-", body ?? "-")}

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

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

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

I tested three casesPush notification:

When the application is disabled
If the user opens the Application Notification, call the didfinishlaunchingwitexceptions method to update, as shown below:

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

If you have already read this notification, the badge is cleared. Then, check whether the application is opened from the icon or through the notification. In the first case, call the registerpushconfigurations () method and continue the previous process. If the application runs by opening the notification, the custom icationicationreceived method is called to Add rows.

When the application runs on the frontend
If the user is using the application, which means the application is on the frontend, the method for receiving the notification is as follows. Add tableView processing to the method of this notification:

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

Note: In this case, the notification will not sound.

When the application runs in the background
In this case, I added a method to clear the number of badge. The processing of notifications is the same as that of applications on the frontend.

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

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

Last

With the notification of iOS 10, developers have more interesting opportunities than before and have no interaction permissions. I hope that this tutorial will help you better understand how notifications work.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.