This article focuses on the basic use of local and remote notifications on iOS, as well as some of the less obvious issues.

Note: Many of the students provide help, a large number of citation or reprint of this article please state the original address, thank you.

I. Introduction to user notification

What is user notification

There are three common Notification methods for events in iOS: NSNofiticationCenter, KVO Notification, and User Notifications, where User Notifications are the User Notifications I’ll explore in this article.

As we all know, iOS system often has some notification bar messages related to App. These messages are often accompanied by a prompt sound and an unread message in the upper right corner of the App desktop icon. These notifications are iOS user notifications.

Classification of user notifications

There are two types of user notifications: local notifications and remote notifications. Remote notifications are also called push notifications.

The main difference between the two is that the local notification is sent to the current device by the App without network support. The remote notification is sent by the App server to the Apple APNs server, and then forwarded by the APNs server to the corresponding device (the device designated by the App server to receive the notification).

The main similarities between local and remote notifications are as follows: Local and remote notifications are expressed in the same way to users. In both cases, users can be notified by notification bar messages, ICONS in the upper right corner of App desktop ICONS, and announcements.

What is the use of user notification

Sending messages (chat messages, news, to-do lists, weather changes, etc.) to users in a timely and efficient manner (whether in the foreground or in the background) is the biggest advantage of user notification.

In addition, the effective and reasonable use of user notification can make our App have a better experience, such as:

  • Remind users when a backlog is about to expire;
  • When the user performs the task of downloading large files, the user can enter the background and be notified when the download is complete.
  • When users travel around the world, they can push weather changes and other information according to their geographical location.
  • Notifies users of updates to a magazine or news topic they subscribe to;

The rest of this article will take an in-depth look at user notifications from the perspective of app developers. This article will focus on ios 7/8/9, and user notifications for iOS10 will be explained separately.

You can download the demo here. In addition, this article uses Simplepush.php for remote notifications. The internal code is very simple and you can use this script to customize the contents of remote notifications. Of course, you can use the script file I modified in the demo. Demo does not provide a certificate. If remote notification is required, apply for a certificate; otherwise, Simplepush cannot be used.

This article mainly refers to apple’s official Local and Remote Notification Programming Guide and the official documentation of the interfaces used in this article.

Two: the use of local notifications

Enable the local notification function

  • For iOS7, if you don’t turn off notifications in the App’s system Settings, you don’t need to do anything to use local notifications.

  • For iOS8 or later, you need to register the notification type to use the local notification function. There are four types of notification: Angle of standard (UIUserNotificationTypeBadge), prompt (UIUserNotificationTypeSound), message (UIUserNotificationTypeAlert) and without any notice (UIUserNotificat IonTypeNone).

    You can register for any combination of the four notification types, but ultimately the type of notification available depends on the user’s notification Settings for the App. For example, if the App registers the horn, prompt sound and prompt message, but the user turns off the sound notification, there will be no prompt sound when receiving the local notification. Example code for registering local notifications for iOS8 and later is as follows:

    - (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (launchOptions NSDictionary *) {/ / only IOS8 and laterif([[UIApplication sharedApplication] respondsToSelector: @ the selector (registerForRemoteNotifications)]) {/ / here types can be customized, If types is 0, then all user notifications are received silently and the user is not prompted (of course, App can handle yourself and give prompt) UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert); // Categories can be covered in detail later in this article. UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil]; / / when the application is installed for the first time this method is invoked, the system will pop-up prompt the user whether to allow the receiving notice [[UIApplication sharedApplication] registerUserNotificationSettings: mySettings]; } // Your own other codes.return YES;
    }
    Copy the code

When the system prompts you whether to allow the user to receive notifications, the user may reject the request. We can the AppDelegate application: didRegisterUserNotificationSettings: Method is used to view the type of notification for successful registration. After receiving the registration result, we can customize the operation (for example, if the user fails to pop up a window indicating that user notification is currently unavailable).

Apple recommends (but does not mandate) that you avoid using unregistered notification types for subsequent local notifications.

- (void)application: (UIApplication*)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { if (notificationSettings.types & UIUserNotificationTypeBadge) { NSLog(@"Badge Nofitication type is allowed"); } if (notificationSettings.types & UIUserNotificationTypeAlert) { NSLog(@"Alert Notfication type is allowed"); } if (notificationSettings.types & UIUserNotificationTypeSound) { NSLog(@"Sound Notfication type is allowed"); }}Copy the code

Sending local Notifications

Sending a local notification involves the following steps:

  1. Register the notification type by following the “Enable local notification” steps above.

  2. Create a UILocalNotification object;

  3. Set the fireDate property of the UILocalNotification object, which indicates when to send the local notification; You can also set the timeZone property to indicate the timeZone. After setting the timeZone, fireDate will be adjusted based on the timeZone (similar to clock adjustment) when users cross time zones. In addition, you can use repeatInterval and repeatCalendar to set up periodic notifications.

  4. Set the notification prompt:

    • Set alertTitle as the summary of the notification and alertBody as the specific information of the notification. Note that it is strongly recommended to use localized strings, i.eNSLocalizedString(@"This is alert body", nil);. Note that the alertTitle attribute applies only to iOS8.2 and later
    • Set applicationIconBadgeNumber for App show desktop ICONS Angle of the upper right corner of the label.
    • Set soundName, we usually set to UILocalNotificationDefaultSoundName; Using custom Sound is explained more later.
    • When setting the value of the reminder mode, for iOS8 or later, check whether the current reminder mode has been registered successfully[[UIApplication sharedApplication] currentUserNotificationSettings]Get registration success notification type).
  5. You can choose to set the userInfo attribute, which can store business-related information (such as ID), so that you can easily process business-related logic after receiving the notification.

  6. Shall notify the queue created above UILocalnotification into: usage scheduleLocalNotification: Will be carried out in accordance with the fireDate UILocalnotification notice to send, and using presentLocalNotificationNow: will send the local notice immediately.

Here is a sample code:

- (void)scheduleLocalNotification { NSDate *itemDate = [NSDate date]; UILocalNotification *localNotif = [[UILocalNotification alloc] init]; if (localNotif == nil) return; localNotif.fireDate = [itemDate dateByAddingTimeInterval:10]; localNotif.timeZone = [NSTimeZone defaultTimeZone]; LocalNotif. AlertBody = [nsstrings stringWithFormat: NSLocalizedString (@ "% % @ after seconds I scheduled.", nil), @ "local notice", 10]; localNotif.alertTitle = NSLocalizedString(@"Local Notification Title", nil); localNotif.soundName = UILocalNotificationDefaultSoundName; localNotif.applicationIconBadgeNumber = 1; NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"ID:10" forKey:@"LocalNotification"]; localNotif.userInfo = infoDict; [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; }Copy the code

Process received local notifications

Here’s how to handle local notifications in three cases:

Application in the foreground

When the application is in the foreground, when the local notification arrives, there will be no prompt sound or notification bar banner prompt. However, the corner mark in the upper right corner of the App desktop icon is displayed with numerical value. Therefore, even in the foreground, we should also deal with the number of diagonal marks. We can in application: didReceiveLocalNotification: method of access to local notice, the sample code is as follows:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSString *itemName = [notification.userInfo objectForKey:@"LocalNotification"]; [self.windowRootController displayNotification:[NSString stringWithFormat:@"%@ receive from didReceiveLocalNotificaition", itemName]]; / / labelled Angle number minus one here, pay attention to the system will not help us deal with Angle of the number of application. The applicationIconBadgeNumber - = 1; }Copy the code

Application in the background

When the application is in the background, local notifications are prompted based on the notification type set by the application or the user, such as lock screen notification, notification bar notification, sound notification, and corner icon notification.

At this point, if you swipe the lock screen to notify or click the notification bar to notify, the application will be switched to the foreground. We can use the same method to obtain the notification as when the application is in the foreground.

However, if we click the App desktop icon, we cannot get the user notification, and the notification bar message will still exist. In addition, the corner tags will not change. If you want to modify the corner tags, you need to modify them after the App enters the foreground.

The application is not running

If the application is not running, when the local notification arrives, the system prompts you based on the notification type set by the local or user, such as the lock screen notification, notification bar notification, sound notification, and corner icon notification. At this point if the slide lock screen interface notice or click on the notification bar, will open the application, but the way we get notification, are different from the front, through application: didReceiveLocalNotification: can’t get notification. This kind of situation we need to pass application: didFinishLaunchingWithOptions: acquisition, the LaunchOptions example code is as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (localNotif) { NSString *itemName = [localNotif.userInfo objectForKey:@"LocalNotification"]; [self.windowRootController displayNotification:[NSString stringWithFormat:@"%@ receive from didFinishLaunch", itemName]]; // custom method [UIApplication sharedApplication].applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1;  } // Your own other codes. return YES; }Copy the code

Similarly, if we click on the App desktop icon, we will not get the user notification, and the notification bar message will still exist. In addition, the corner tags will not change. If you want to modify the corner tags, you need to modify them after the App enters the foreground.

Location-specific local notifications

In iOS8 and beyond, we can define a location-specific local notification so that when we cross a set geographic area, the system will send a local notification.

Register location-specific local notifications

  1. You need to create a CLLocationManager object and set a delegate for it;

  2. Request user permission to use location service: Call the CLLocationManager requestWhenInUseAuthorization, pay attention to the project need to be configured in the plist NSLocationWhenInUseUsageDescription options, Otherwise, the location service cannot be enabled. Example code is as follows:

    - (void)registerLocationBasedNotification { CLLocationManager *locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; / / the application location permissions [locationManager requestWhenInUseAuthorization]; }Copy the code
  3. Through the CLLocationManagerDelegate callback check whether the user is allowed to use location services, if the service is allowed, you can send a position related to local notification.

    - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { // Because we are using the requestWhenInUseAuthorization above, So here to check the kCLAuthorizationStatusAuthorizedWhenInUse if (status = = kCLAuthorizationStatusAuthorizedWhenInUse) {[self scheduleLocalBasedNotification]; }}Copy the code
  4. Create a location-specific local notification and submit it to the system for processing.

    - (void)scheduleLocalBasedNotification { UILocalNotification *locationNotification = [[UILocalNotification alloc] init];  Arrive locationNotification. AlertBody = @ "XXX"; locationNotification.regionTriggersOnce = NO; / / said crossing the designated area will send notification locationNotification. Region = [[CLCircularRegion alloc] initWithCenter: LOC_COORDINATE radius:LOC_RADIUS identifier:LOC_IDENTIFIER]; [[UIApplication sharedApplication] scheduleLocalNotification:locNotification]; }Copy the code

Handles location-specific local notifications

Compared with “Processing received local notifications”, this region can be obtained from the notification and customized operations can be performed. All other operations are consistent with “Processing received local notifications”.

Note If the user does not have permission to use location, the user cannot receive local notifications related to location.

Three: the use of remote notification

APNs profile

APNs is the remote notification server provided by Apple. When the App is in the background or not running, if the App server (later called Provider) needs to send notification information to the client, it needs to use the APNs server.

When the APNs service is used, the route path for remote notification is Provider > Apple APNs server > Mobile device > App. In this path, there is a TLS connection between the Provider and the APNs server. The Provider pushes remote notifications to the APPLE APNs server through this connection. There is also a TLS connection between the mobile device and the APNs server. All remote APNs notifications sent to the mobile device use this TLS connection. Then, the device identifies the App to which the remote notification belongs and notifies the user of the remote notification.

Here is a brief introduction to the process:

Equipment with APNs

The connection process between the device and APNs is shown as follows:

Points to be made clear:

  1. This connection is established and maintained by the system without developer management;
  2. The certificate in the figure above is the certificate of the Apple device itself, and has nothing to do with the certificate applied in the developer account;
  3. Each device only needs to maintain one connection to the APNs server.

The Provider and the APNs

The connection between the Provider and APNs is as follows:

Points to be made clear:

  1. This connection is uniquely determined by the App’s Bundle ID;
  2. In the figure above, Provider certificate needs to be applied and generated through the developer account, which contains the bundle ID of App.

APNs workflow

  1. First, the client needs to register the current App with the APNs server. APNs will return a Token(note that this process requires the App to have a valid certificate, which is not described in detail here). Notice Different applications obtain different tokens on the same device, and the same application obtains different tokens on different devices. Therefore, the Token is uniquely bound to the device and App.

  2. After the App gets the Token, it needs to send it to the Provider.

  3. When the Provider sends push notifications, it specifies the Token and notification content and sends them to the APNs server.

  4. The APNs server sends the notification to the device corresponding to the Token.

  5. After receiving the notification, the device identifies the remote notification from which App according to the bundleID information contained in the notification sent by APNs (the device should obtain the bundleID based on the Token).

Feedback mechanism

Feedback is a service provided by APNs server to reduce server pressure and optimize network. The basic working process is shown as follows:

  1. The Provider sends a remote notification to the APNs server. The APNs server checks whether the destination device is online. If not, the APNs server stores the message temporarily.

  2. When the destination device goes online, APNs sends a temporary message to the destination device. (According to Apple’s official saying, a temporary message only stores the last message and the previous message is discarded.)

  3. If the destination device has not been online for a long time, the APNs message adds the device to the feedback list. The Provider can regularly go to APNs to get a new feedback list;

  4. When the Provider sends a remote notification to the previous device again, it needs to check the feedback list. If the device is in this list, it will not send to APNs.

  5. When the device comes back online, the Provider can remove the device from the feedback list. When the Provider updates the feedback list, it can send remote notifications to the device again. Of course, the update of the feedback list may take place periodically. If the feedback list needs to be updated in a timely and effective manner, the Provider shall be notified in time after the App is opened.

  6. The advantage of this mechanism is to prevent unnecessary remote notification messages from being sent. On the one hand, it can reduce the pressure on the APNs server, and on the other hand, it can reduce network traffic.

Enable the remote notification function

Registration Notification Type

  • For iOS7, skip this step.
  • For iOS8 or later, you need to register the notification type if you want to use the remote notification function. The procedure is the same as “Enabling local notification” in “Using local Notification”.

Register remote notification

The basic process is:

  1. Register notification types, as described in the previous section;
  2. useregisterForRemoteNotificationsRegister remote notifications (for iOS7 useregisterForRemoteNotificationTypes:);
  3. useapplication:didRegisterForRemoteNotificationsWithDeviceToken:The Token returned by APNs is usedapplication:didFailToRegisterForRemoteNotificationsWithError:Handle registration errors;
  4. If the registration was successful in the previous step, the resulting Token is sent to the Provider.

Note:

  1. For iOS9, the Token will be different each time the app is reinstalled, and the system will change each time the app is reinstalled. Therefore, you need to register the Token once each time the app is launched.

  2. Don’t put the Token of the cache before, when need to transfer Token to the Provider, must use registerForRemoteNotifications to obtain, and USES the callback to handle the registration results; When the application registers the notification and the Token does not change, the system returns the result immediately and does not request APNs. If the current status of the application does not change, the Token saved in the system will be returned immediately. To prove this, you can shut down the network for testing. If the App is not uninstalled, you can also obtain Token.

  3. You must have a certificate with Push enabled for remote Push to work properly.

Example code for registering remote notifications is as follows:

- (void) registerRemoteNotifications {/ / distinguish whether iOS8 or later if ([[UIApplication sharedApplication] RespondsToSelector: @ the selector (registerForRemoteNotifications)]) {/ / here types can custom, if the types of 0, so all users receive notification will silence, The user is not prompted (of course, App can handle yourself and give prompt) UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert); // Categories can be covered in detail later in this article. UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil]; / / when the application is installed for the first time this method is invoked, the system will pop-up prompt the user whether to allow the receiving notice [[UIApplication sharedApplication] registerUserNotificationSettings: mySettings]; } else { UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound; [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types]; } } - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(nonnull UIUserNotificationSettings *)notificationSettings { // Register for remote notifications. [[UIApplication sharedApplication] registerForRemoteNotifications]; } // Handle register result. - (void)application:(UIApplication *)application DeviceToken didRegisterForRemoteNotificationsWithDeviceToken: (NSData *) {/ / get the device token, This is a very important step in processing for the operation of the string nsstrings * token = [[[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"DeviceToken string, %@", token); [UIApplication sharedApplication].applicationIconBadgeNumber = 0; // send the token to Provider} - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"Error in registration for apns service. Error: %@", error); }Copy the code

Sending remote Notifications

Contents of remote notifications

The Provider sends the content to the APNs server in the following format:

{// aps key is mandatory. "aps" : {"alert" : {"title" : "summary of the notification. This option is invalid for pre-8.2 systems." "body" : "specific content of the notification ", "loc-key" : "GAME_PLAY_REQUEST_FORMAT", "LOC-args" : ["Jenna", "Frank"]}, "badge" : 3, // "Chime. aiff" // You can customize the prompt tone}, "userName" : "userName", // You can customize content other than the APS key, which must be in json format. "message" : ["hello", "world", "programmer"] }Copy the code

The above is a brief description of common content. For more in-depth notification customization, check out the official Apple Payload document

Localized handling of remote notifications

There are two ways:

  • The App can send the current language to the Provider. Before sending the remote notification, the Provider checks the language used by the device and sends the localization to the APNs server. Example code for the App to send the currently used language to the Provider:

    NSString *preferredLang = [[NSLocale preferredLanguages] objectAtIndex:0];
    const char *langStr = [preferredLang UTF8String];
    [self sendProviderCurrentLanguage:langStr]; // custom method
    Copy the code

    Generally speaking, when the current system language information is sent to the Provider, the Token is also sent, so that the Provider can send remote notification localized according to the destination device. In addition, when the application starts, the user may modify the system language, at this time, the App needs to monitor NSCurrentLocaleDidChangeNotification notice, and again in the method of dealing with the notification to the Provider sends the current use of language.

  • In client-side localization mode, the Provider needs to set the localization attribute Payload -> alert when sending remote notifications.

    {// aps key is mandatory. "aps" : {"alert" : {"title" : "summary of notification. This option is not valid for pre-8.2 systems ", "loc-key" : "Remote Notification", "Loc-args" : ["hello", "world"]}, "badge" : 3, // "sound" : "chime.aiff" //Copy the code

Loc-key and loc-args above are localization related attributes for the body in the localization Alert. When the App receives this message, it will search for the value corresponding to loc-key in the corresponding localization file according to the current language Settings of the system. If the value corresponding to loc-key is a formatted string, then loc-args can be used to pass parameters.

If “Remote Notification” = “we programmers usually prefer: %@ %@” in the localization file, the prompt is:” We programmers prefer: hello world”;

We can also use %n in localization files@% 1$@”, then prompt message: “We programmers love: world hello”.

Similarly, title-loc-key and title-loc-args localize the title in alert.

Process received remote notifications

Here’s how to handle remote notifications in three cases:

Application in the foreground

When the application is in the foreground, there is no notification sound or notification bar banner when the local notification arrives. However, the corner icon in the upper right corner of the App desktop is displayed with a numerical value, so even in the foreground, we should also deal with the number of corner ICONS. At this point, we can in application: didReceiveRemoteNotification: fetchCompletionHandler: method of access to remote notifications, the example code is as follows:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler { NSData *infoData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:nil]; NSString *info = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding]; [self.windowRootController displayNotification:[NSString stringWithFormat:@"From didReceiveRemoteNotification: %@", info]]; / / labelled Angle number minus one here, pay attention to the system will not help us deal with Angle of the number of application. The applicationIconBadgeNumber = notification. ApplicationIconBadgeNumber - 1; }Copy the code

Application in the background

When the application is in the background, the remote notification will be prompted according to the notification type set by registration and user, such as lock screen notification, notification bar notification, sound notification, and corner icon.

At this point, if you swipe the lock screen to notify or click the notification bar to notify, the application will be switched to the foreground. We can use the same method to obtain the notification as when the application is in the foreground.

However, if we click the App desktop icon, we cannot get the user notification, and the notification bar message will still exist. In addition, the corner tags will not change. If you want to modify the corner tags, you need to modify them after the App enters the foreground.

The application is not running

There are two ways to handle this:

  • With local notification processing in the same way, in the application: didFinishLaunchingWithOptions: LaunchOptions get notification, but internal code will be slightly different, sample is as follows:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    	NSDictionary *remoteNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    	if (remoteNotif) {
        	NSData *infoData = [NSJSONSerialization dataWithJSONObject:remoteNotif options:0 error:nil];
        	NSString *info = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
        	[self.windowRootController displayNotification:[NSString stringWithFormat:@"From didFinishLaunch: %@", info]];
        	[UIApplication sharedApplication].applicationIconBadgeNumber -= 1;
    	}
    	// Your own other codes.
    	return YES;
    }
    Copy the code
  • Same as the application in Taiwan before and after treatment, using application: didReceiveRemoteNotification: fetchCompletionHandler: method, sample code see when applied at the front desk, the processing. This method is recommended for remote notifications.

    In addition, for remote notifications, if we click on the App desktop icon, we cannot get the user notification, and the notification bar message will still exist. In addition, the corner tags will not change. If you want to modify the corner tags, you need to modify them after the App enters the foreground.

Remote notification – Silent push

Silent push refers to the application in the foreground or background state, when receiving remote notification, there is no pop-up window or banner prompt, even in the background can also process remote notification. The specific use process is as follows:

  1. Open the App Target, open the Background Modes option, and check Remote Notifications.

  2. When the Provider sends remote notifications, set content-available in the APS Payload to 1, as follows:

     aps {  
         content-available: 1
         alert: {...}
     }
    Copy the code
  3. Application needs to implement application: didReceiveRemoteNotification: fetchCompletionHandler: push method receives the silence.

A few things to note:

  1. When silent push is used, the alert field should not have any information, but you can set the aps custom field;
  2. Sound and badge fields can be set, but it is best not to set, otherwise there will be a prompt sound;
  3. Silent push can be processed only when the application is in the foreground or background. When the application is not started, silent push cannot be received.
  4. Do not perform time-consuming operations during silent push because the system allocates only a small amount of time for such operations. For example, download files using the background download service.

Operational notice

The first thing to note is that actionable notifications only work with iOS8 and later.

Actionable notification is not really a new form of notification, it just adds actionable behavior to the local and remote notifications. To illustrate what actionable notifications are, consider the following figure:

Actionable notification provides users with a convenient way to perform operations in the notification prompt. A maximum of two operations can be performed when a banner notification message is used, and a maximum of four operations can be performed when a pop-up notification message is used. Here’s how to use it:

Define the behavior of actionable notifications

Basic usage:

  1. Create a UIMutableUserNotificationAction object and on-demand configuration is the attribute of the object, the sample code:

    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init]; // Set an id acceptAction.identifier = @"accept"; Acceptaction. title = @"Accept"; / / specify whether need to apply in the running state acceptAction. ActivationMode = UIUserNotificationActivationModeBackground; // Indicates whether this action is harmful. If set to YES, the corresponding button will have acceptAction.destructive = NO; / / when the lock screen after notice of operational, this property indicates whether or not have to unlock to perform this operation acceptAction. AuthenticationRequired = YES;Copy the code
  2. Create a UIMutableUserNotificationCategory object, and the custom operation through setActions: the way of object set to the category. The code is as follows:

    // Create two new actions, declineAction and maybeAction, Demo code visible UIMutableUserNotificationCategory * inviteCategory = [[UIMutableUserNotificationCategory alloc] init]; / / set an ID, or remote notifications for local notice specifying the notice executable operation group inviteCategory. The identifier = @ "Action"; // setActions for popover mode [inviteCategory setActions:@[acceptAction, maybeAction, declineAction] forContext:UIUserNotificationActionContextDefault]; // setActions for banner mode [inviteCategory setActions:@[acceptAction, declineAction] forContext:UIUserNotificationActionContextMinimal];Copy the code
  3. Register notification types and actions that can be acted on

    Similar to notify the local and remote notifications, call registerUserNotificationSettings: registration notice, just setting here to join the category we defined above.

    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil]; // Here the types can be customized. If the types is 0, all user notifications will be received silently, and no hint will be given to the user. App can handle yourself and give prompt) UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert); // Categories can be covered in detail later in this article. UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories]; / / when the application is installed for the first time this method is invoked, the system will pop-up prompt the user whether to allow the receiving notice [[UIApplication sharedApplication] registerUserNotificationSettings: mySettings];Copy the code

If executable notification is used for remote notification, you need to obtain the token according to the remote notification registration method. For details, see Remote notification Registration.

Send actionable notifications

As mentioned earlier, actionable notifications simply add custom actions to local and remote notifications, so sending actionable notifications is just sending local or remote notifications. However, if we want our custom action to work, we need to make some changes when sending local or remote notifications:

  • Actionable notifications for local notifications set our custom category for the UILocalNotification object. As follows:

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // Other configurations
    notification.category = @"Action";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    Copy the code
  • In the Payload of the remote notification, set the following user-defined categories:

    {
        "aps" :  {
            "alert" : "You 're invited!"."category" : "Action"}}Copy the code

Handle actionable notifications

Handling actionable notifications is the same as handling local and remote notifications, except that when a user performs an action, Applications can run in the background application: handleActionWithIdentifier: forRemoteNotification: completionHandler: To handle notifications (such as background updates), we can quickly perform operations in this callback:

- (void)application:(UIApplication *) application handleActionWithIdentifier: (NSString *) identifier // either forLocalNotification: (NSDictionary *) notification or forRemoteNotification: (NSDictionary *) notification completionHandler: (void (^)()) completionHandler { if ([identifier isEqualToString: @"accept"]) { [self handleAcceptActionWithNotification:notification]; } // completionHandler() must be called after executing the custom code; }Copy the code

For local notice we can use the application: handleActionWithIdentifier: forLocalNotification: completionHandler:.

What are the benefits of actionable notifications?

Here is an example to illustrate: If A sends an invitation to B to attend A press conference, and the App receives the information in the form of remote notification, what we need to do when the actionable notification is not used mainly includes:

  1. The user needs to open the app;
  2. The content of the remote notification viewed by the App is an invitation, so the App should pop up a window to prompt the user whether to accept the invitation.
  3. After the user selects, the App returns the result to the server through Http(or other communication protocols).
  4. Invitation notification processing is complete.

So, if we use actionable notifications, we can do this very easily:

  1. Users choose to accept or reject the invitation (users do not need to open the App);

  2. App processes user operation results through the callback of actionable notification and sends the results to the server.

  3. Invitation notification processing is complete.

    As you can see, actionable notifications are a great way to handle notifications with actionable actions, both from a user’s perspective and from a developer’s perspective.

Five:

The content of user Notification has been explained here. The article contains all the basic usage of user Notification provided by Apple. If you want to confirm whether the documentation is wrong, please refer to Local and Remote Notification Programming Guide. Welcome to point out and discuss.