IOS10 Push Notification development tutorial _php instance

Source: Internet
Author: User

Although notifications are often overused, notifications are indeed an effective way to get users to focus on and inform them of the need for updates or actions. IOS 10 has new notifications, such as new messages, business information, and schedule changes. In this tutorial, I'll show you how to use notifications in your iOS app, and show iOS 10 introducing new features. Developing iOS 10 push notification You need the latest version of Xcode,xcode 8 Beta, which is currently downloadable on the download page.

You can go to GitHub to download the entire project for this tutorial.

Begin

It's easy to enable push notifications in Xcode, but you need a few steps.

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

When you have created project, go to the Project Settings page to select the capabilities bar. Turn on push notifications as shown below.

Note: If you are an Apple paid developer, you can see the push Notification feature column.

To developer account This column, select the certificate, IDs, and Description files from the menu bar on the left, and then select App IDs in the identifiers column. Locate the name of the app you've created and select it in the list of services. Note that there are two push notifications that can be configured.

Don't close this page, you'll 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, send a notification and you will need a certificate.

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

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

Return to the Developer Account page. You can generate a development (debug) certificate or issue certificate for your app IDs.

After the application on the right side of the selection, at the bottom, click Edit. In the Push notification section, click Create Development (Debug) certificate.

Continue uploading to generate certificate requests, as needed, from keychain.

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

Download and run the pusher. The top of this program needs to fill in a push certificate. For it to be located in your key chain, OS X will ask if pusher is allowed access to the certificate.

The second field requires device token, and you'll have to hit it in the next step.

Receive notification

It's time to hit the code. The device receiving the notification must be registered with the Apple Push Notification Service (APNS). You have to send a unique token when the application is started.

Open Appdelegate.swift and add the following method.

Note: This code is based on Swift3.0. The syntax may look different from what you've 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 application-initiated file.

Func Application (_ Application:uiapplication, didfinishlaunchingwithoptions launchoptions: [Nsobject:anyobject]?)- > Bool {
 registerpushnotifications () return
 true
}

At this point, the application automatically pops up an alert asking the user if they want to receive the notification.

The notification must be registered before it can be sent, and the user's approval is required to accept the notification. The Uiapplicationdelegate method handles the response.

Func Application (_ Application:uiapplication, Didregister notificationsettings:uiusernotificationsettings) {
 if Notificationsettings.types!= Uiusernotificationtype () {
 application.registerforremotenotifications ()
 }
}

First check the user grant permission, and then call the method to register the remote notification. When the request completes, the other proxy method is invoked. This method response contains a device token that you can print for debugging. In sending push notifications to identify the device requires this device token.

If an error occurs, call the following method.

Func Application (_ Application:uiapplication, Didfailtoregisterforremotenotificationswitherror error:nserror) {
 Print ("Registration failed!")
}

Note: It is important to invoke registerusernotificationsettings when the application starts, because the user can change the settings of the permission. The same registerforremotenotifications is also important because some scenes device token can be changed so that notifications will not be sent.

So far, it's enough to get you a simple notice.

Notification content

With different notification content, there are different ways to get an app to receive different types of notifications, which include information that the application notifies the user, or user-defined information.

Send a notification to the user using the JSON format, which itself contains a dictionary corresponding to the APS key. In this second dictionary you specify the contents of the load and key.

The most common are:

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

A simple notification content for this tutorial:

{"
 APs": {"alert": {"
 title": "Hello!:)",
 "body": "App closed ..."
 },
 "badge": 1,
 "sound ': ' Default '
 }
}

The life cycle of the application

The copy device token is pasted in the token part of the pusher and copies this JSON object in the Pusherd part of the payload.

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

To receive 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 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
 view? AddNotification (
 Title:getalert (notification:notification). 0,
 body:getalert (notification: notification). 1)
}

This method adds a row to the main view uitableview of the application (see Viewcontroller's full project code).

I tested the push notifications for three cases:

When the application is closed
If the user opens the application notification, invoke the Didfinishlaunchingwithoptions method update as follows:

Func Application (_ Application:uiapplication, didfinishlaunchingwithoptions launchoptions: [Nsobject:anyobject]?)- > Bool {
 //Override customization after application launch.
 Application.applicationiconbadgenumber = 0; Clear badge when app launches
 //Check if launched to notification
 if let notification = launchoptions?[ Uiapplicationlaunchoptionsremotenotificationkey] as? [String:anyobject] {
 window?. Rootviewcontroller? Present (Viewcontroller (), Animated:true, Completion:nil)
 notificationreceived (notification:notification)
 else {
 registerpushnotifications ()
 } return
 true
 }

Assuming the user has seen the notice, the corner mark is cleared. Then, check that the application is open from the icon or by notification. In the first case, call the Registerpushnotifications () method and proceed to the previous process. If the application is run by opening the notification, the custom notificationreceived method is invoked to add the row.

When the application is running in the foreground
If the user is using the application, this means that the application is in the foreground, and the method for receiving the notification is as follows. Add the processing to the TableView in the method of this notification:

Func Application (_ Application:uiapplication, didreceiveremotenotification userInfo: [Nsobject:anyobject]) {
 Notificationreceived (notification:userinfo)
}

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

When the application is running in the background
In this case, I added a method to clear the number of corners. The processing of notifications is the same as the processing of applications at the front desk.

Func Applicationwillenterforeground (_ application:uiapplication) {
 application.applicationiconbadgenumber = 0; /clear badge When app is or resumed
}

Finally, the list contains three lines of content from the notification.

At last

With the iOS 10 notification, developers have more interesting opportunities than before and have no interaction privileges. I hope this tutorial on how to use alerts will help you better understand how notifications work.

This article has been organized into the "iOS push Tutorial", welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.