introduce

The User Notifications Framework was launched by Apple at WWDC 2016. IOS 10 clutter before and inform related apis are unified, developers can now use independent UserNotifications. Framework to centrally manage and use the function of notification in iOS. On this basis, Apple also added a series of new functions, such as withdrawing a single notice, updating the displayed notice, modifying the content of the notice midway, showing pictures and videos in the notice, and customizing the notice UI, which are very powerful.

Previous iOS 10 push

Previously, iOS 10 Notifications were split into Local Notifications and Remote Notifications.

Local push: add it to the Schedule of the system through App local customization, and then push the specified text at the specified time. .



Remote Push: The server sends the Notification Payload to the Apple Push Notification Service (APNs), and the APNs sends the Notification Payload to the specified App on the specified device.



User Notifications Framework

The basic configuration

If it is a simple local push, skip steps 1 and 2 and go straight to Step 3.

1. If your App has remote push, you will need a developer account and a new push certificate corresponding to your bundle. In XCode7, Push Notifications should be enabled, but in XCode8, Push Notifications must be enabled, otherwise an error will appear:

Error Domain=NSCocoaErrorDomain Code=3000 "Authorization string for application 'aps-Environment' not found"UserInfo={NSLocalizedDescription= Authorization string for "aps-environment" of application not found}Copy the code



Permission to apply for

When using the UserNotifications framework API, first import the UserNotifications framework:

#import <UserNotifications/UserNotifications.h>
Copy the code

Registered push

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if(! error) { NSLog(@"Request for authorization successful");
        }
        else
        {
            NSLog(@"Request for authorization failed"); }}];Copy the code

Notification Settings: We have no way of knowing whether the user signed up for the Notification service, whether the user clicked “Agree” or “disagree”, or what changes the user has made since then. Now apple has opened up the API and we can directly access the user Settings. Note that UNNotificationSettings is a read-only object and cannot be changed directly. You can obtain the value in the following ways only

[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    NSLog(@"% @", settings);
}];
Copy the code

print

<UNNotificationSettings: 0x6000022f9dc0; 
authorizationStatus: NotDetermined, 
notificationCenterSetting: NotSupported, 
soundSetting: NotSupported, 
badgeSetting: NotSupported, 
lockScreenSetting: NotSupported, 
carPlaySetting: NotSupported, 
criticalAlertSetting: NotSupported, 
alertSetting: NotSupported, 
alertStyle: None, 
providesAppNotificationSettings: No>
Copy the code

Token Registration

[[UIApplication sharedApplication] registerForRemoteNotifications];
Copy the code

Obtain the Device Token of the Device

// obtain DeviceToken successfully - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *deviceString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"< >"]];
    deviceString = [deviceString stringByReplacingOccurrencesOfString:@"" withString:@""];
    NSLog(@"deviceToken:%@",deviceString); } // failed to obtain DeviceToken - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"[DeviceToken Error]:%@\n",error.description);
}
Copy the code

Proxy method to receive push

// Only when the App is in the foreground state will be called, - (void)userNotificationCenter:(UNUserNotificationCenter *)center - (void)userNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions Options))completionHandler // App notification click event // triggered only when the user clicks on the message - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandlerCopy the code

Apple has combined local and remote notifications. Distinguish between local notice with remote class is UNPushNotificationTrigger h class, UNPushNotificationTrigger types are added.

UNPushNotificationTrigger (remote notifications) of the remote push notification type UNTimeIntervalNotificationTrigger (local notification) after a certain time, repeat repeat push notification or not. We can set timeInterval and repeats. UNCalendarNotificationTrigger (local notification) after a certain date, repeat repeat push notification or not For example, you push a notification at 8 o ‘clock every day, as long as dateComponents of 8, if you want to push this notice at 8 o ‘clock every day, As long as repeats is YES. UNLocationNotificationTrigger (local notification) geographic location of a notice, when a user enters or leaves a geographical area to notice.

content

Instead of displaying only one text, you can now display title, subtitle, and body.



The customization method is as follows:

/ / local notifications UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc] init]; content.title = @"CALENDAR";
content.subtitle = @"Lunch";
content.body = @"Today at 12:00 PM"; content.badge = @1; // remote push {"aps" : {
    "alert" : { 
         "title" : "CALENDAR"."subtitle" : "Lunch"."body" : "Today at 12:00 PM"
                },
    "badge": 1}}Copy the code

Triggers

UNTimeIntervalNotificationTrigger timed push UNCalendarNotificationTrigger push UNLocationNotificationTrigger fixed-point push on a regular basis

// Remind after 60 seconds //timeInterval: units are seconds (s) repeats: Whether circulating remind UNTimeIntervalNotificationTrigger * trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval: 60 repeats:NO]; // Remind NSDateComponents * Components = [[NSDateComponents alloc] init] every Monday at 8:00 am; components.weekday = 2; components.hour = 8; UNCalendarNotificationTrigger *trigger3 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES]; // Import it first# import < CoreLocation/CoreLocation. H >, or you'll regin create has a problem.CLLocationCoordinate2D center1 = CLLocationCoordinate2DMake (31.234567, 117.4567890); CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center1 radius:500 identifier:@"Guilin Road"];
UNLocationNotificationTrigger *trigger4 = [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO];
Copy the code

Add Request

NSString *requestIdentifier = @"sampleRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier
                                                                          content:content
                                                                          trigger:trigger1];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

}];
Copy the code

Push summary

The whole push process is as follows



Local Notifications are implemented by defining Content and Trigger requests to UNUserNotificationCenter. Remote Notifications send Notification payloads to APNs.

Notification Handling

You set up a push, and that’s it? IOS 10 is not that simple! By implementing the protocol, the App can capture and process the push to be triggered when it is in the foreground:

@interface AppDelegate () <UNUserNotificationCenterDelegate>

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
}
Copy the code

Make it display only Alert and sound, ignoring badge.

Notification Management

Take full control of the entire push cycle:

Local Notification Via update request Remote Notification via the new field apns-collapsing-id

The original push can be refreshed by adding it again with the same ID using the previous addNotificationRequest: method.

NSString *requestIdentifier = @"sampleRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier
                                                                      content:newContent
                                                                      trigger:newTrigger1];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

}];
Copy the code

Delete schedule push:

[center removePendingNotificationRequestsWithIdentifiers:@[requestIdentifier]];
Copy the code

In addition UNUserNotificationCenter. H and remove all push, view has been deleted from the push, push already issued, and so on strong interface.

After updating the original push, there will be corresponding changes in the display of the notification center. Note the second message here. Now the score is 1:0



The score was refreshed to 1:1 and the position was brought forward without any new push entries!



In iOS 10, the User Notifications Framework needs to be used in iOS 8 and 9. In iOS 10, the User Notifications Framework needs to be used in iOS 8 and 9. Compatible with iOS 8-12 system, access is very simple, 3 lines of code can be done push.

MPushNotificationConfiguration *configuration = [[MPushNotificationConfiguration alloc] init];
configuration.types = MPushAuthorizationOptionsBadge | MPushAuthorizationOptionsSound | MPushAuthorizationOptionsAlert;
[MobPush setupNotification:configuration];
Copy the code

At the same time, MobPush supports diversified push scenarios, user group, AB test, intelligent push and other functions, as well as a complete data statistics background to learn more about the real-time use of APP and users from multiple dimensions