Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement push Notification in iOS10

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to achieve iOS10 push notification, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Start

Enabling push notifications in Xcode is easy, but you need a few steps.

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

When you have created the 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 member of Apple, you can see the push notification function.

Go to the Developer Account column, select the 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 App you have created and select it in the list of services. Notice that there are two push notifications with configurable status.

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, you need a certificate to send a notification.

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

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

Return to the web page of the developer account. You can generate development (debug) certificates or publish certificates for your App IDs.

After selecting the application on the right, at the bottom, click Edit. In the push Notification section, click create Development (Debug) Certificate.

Continue to upload and generate certificate requests from Keychain as needed.

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

Download and run Pusher. The top of this program needs to fill in a pushed certificate. For it to be on your keychain, OS X will ask if Pusher is allowed to access the certificate.

The second field requires device token, which you will have to type in the next step.

Receive notification

It's time to hit the code. Devices that receive notifications must register with Apple's push Notification Service (APNS). You need to send a unique token when the application starts.

Open AppDelegate.swift and add the following methods.

Note: this code is based on Swift3.0. The grammar may look different from what you have used before.

Func registerPushNotifications () {DispatchQueue.main.async {let settings = UIUserNotificationSettings (types: [.badge, .alert, .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 point, the application will automatically pop up an Alert, asking the user if they want to receive the notification.

Notifications must be registered before they can be sent, and whether or not 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 ()}}

First check the permissions granted by the user, and then call this method to register the remote notification. The latter invokes another proxy method when the request is completed. This method response contains a device token that you can print for debugging. Send a push notification to identify that the device needs 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 call registerUserNotificationSettings when the application starts, because the user can change the permission settings. RegisterForRemoteNotifications is also important because there are scenarios where device token can be changed and notifications will no longer be sent.

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

Notification content

There are different ways for an App to receive different types of notifications through different notification contents, including information that the application notifies the user, or user-defined information.

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

The most common ones are:

The notification message displayed to the user. This is a simple string, or a dictionary key like title, body, etc.

The sound of a notification was received. It can be a custom sound, or a system sound.

The number of corner marks in the upper-right corner of the applied icon. Set it to 0 to eliminate the corner mark.

Valid content. Send a silent notification to the user with a value of 1. 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 for this tutorial:

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

The life cycle of the application

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

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

To accept 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 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 line to the main view of the application, UITableView (see the complete project code for ViewController).

I tested push notifications for three cases:

When the application is closed

If the user opens the notification of the application, call the didFinishLaunchingWithOptions method to update, as follows:

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}

Assuming that the user has already seen the notification, the corner mark is cleared. Then, check whether the application is opened from the icon or through notification. In the first case, the registerPushNotifications () method is called and the previous process continues. If the application is running by opening the notification, the custom notificationReceived method is called 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 receives notifications as follows. Add the processing of tableView 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 make a sound.

When the application is running in the background

In this case, I added a method to clear the number of corner marks. Notifications are handled in the same way as applications are handled at 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 contents of the notification.

Thank you for reading this article carefully. I hope the article "how to achieve iOS10 push Notification" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report