preface

Sorting out the content of the message notice separately, but because of work (on) doing (is) (very) matter (lazy) did not update the article, contrary to their original intention of learning. Because the Internet must have a sense of crisis, perhaps eyes open, we will.

IOS 10 UserNotifications secret summary image source net.jpeg

“The Wolf, he is not as strong as the lion or the tiger, nor as big as the elephant, but at least: I never see them in the circus.”

Maybe only the Wolf has been running, which is why I always like it, to keep running like a Wolf, to survive!

After seeing the master of the building installed a good X, I will sum up a little you all know the knowledge point of notice!

In iOS 10, UserNotifications can be classified as “UserNotifications”

background

IOS10 new features out, the various gods have long studied the new features to the scene intelligence benefits (alas, I am just a white). I’ve also been scheduled for iOS10 push!

Apple said this is our biggest release yet for iOS, including a smarter and more open Siri, enhanced 3D Touch support for apps, HomeKit, call blocking and new notifications.

IOS multifarious push notification before 10 will be unified into UserNotifications. The framework to centralized management and use of notifications, add some practical function, the withdrawal notice a single, update has notice, midway modification, shown in the notice of multimedia resources, custom UI, and other functions, It’s really powerful!

This article is mainly about iOS 10 notification, so a lot of the code has not been added to iOS 10.

The basic principle of

IOS Notifications can be divided into Local Notifications and Remote Notifications. (The schematic is from the network, please inform me if there is any infringement, I will add the source, I’m afraid I can’t afford it.)

Local Notifications

Local Notifications. PNG is the summary of iOS 10 UserNotifications

Remote Notifications are created locally in App and added to Schedule of system. If the trigger condition is reached, the corresponding message content will be pushed.

Remote notifications1.jpg for iOS 10 UserNotifications

In the picture, Provider refers to the Push server of an iPhone software. In this article, I will use APNS Pusher, which I bought for 12 dollars, as my Push source.

APNS stands for Apple Push Notification Service (Apple Push Server).

The figure above can be divided into three stages:

Phase 1: The APNS Pusher application packages the message to be sent, with the identity of the destination iPhone, and sends it to APNS.

Stage 2: APNS looks for iphones with corresponding logos in the list of iphones registered with Push service and sends the message to iPhone.

Phase 3: The iPhone delivers the incoming message to the appropriate application and pops up a Push notification.

Remote notifications2.jpeg is a summary of iOS 10 UserNotifications

From the picture above, we can see:

The first is the application registration notification push. IOS requires deviceToken from APNS Server. The application accepts deviceToken. The application sends deviceToken to the PUSH server program. The server sends a message to the APNS service. The APNS service sends the message to the iPhone app. Basic configuration and basic methods

If it’s a simple local push, skip steps 1 and 2 and go straight to 3

1. If your App has remote push, you will need a developer account and a new push certificate corresponding to your bundle. Certificate this I will not say, if there is any question about the certificate can give me a message, I will separate the certificate related knowledge points sorted up! If you don’t have an account, you can buy one from a certain treasure. It’s very cheap.

2. Enable Push Notifications in Capabilities

In XCode7, this switch is not turned on, and push can be used normally, but in XCode8, this switch must be turned on, otherwise an error will be reported:

ErrorDomain =NSCocoaErrorDomain Code=3000 “Authorization string for application ‘aps-environment’ not found” UserInfo={NSLocalizedDescription= Not found application “aps-environment” authorization string} open will automatically generate Entitlements file in the project.

IOS 10 UserNotification Secret summary Push Notification switch. PNG

IOS 10 UserNotifications secret summary entitlements file. PNG

3. Push registration

Step 1: import the # import < > UserNotifications/UserNotifications. H

And the protocol to follow is in appdelegate.m.

One thing to note here is that it is best to write it in this form (in case the lower version fails to find the file).

# # ifdef NSFoundationVersionNumber_iOS_9_x_Max import < UserNotifications/UserNotifications. H > # endif step 2: we need to

  • (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) registered in the launchOptions notice, the code is as follows

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self replyPushNotificationAuthorization:application]; return YES; } #pragma mark – pragma mark

  • (void)replyPushNotificationAuthorization:(UIApplication *)application{

if (IOS10_OR_LATER) { //iOS 10 later UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; Delegate = self; // Delegate = self; // Delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (! Error && granted) {/ / users click on allow NSLog (@ “registration”);} else {/ / user clicks do not allow the NSLog (@ “registration failed”);}}];

/ / can get permissions through getNotificationSettingsWithCompletionHandler / / before registration notification service, users click on the agree or disagree, and the user and then do what kind of changes we have no way of knowing, Now that Apple has opened up the API, we can access user Settings directly. Note that UNNotificationSettings is a read-only object and cannot be changed directly. [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { NSLog(@”========%@”,settings); }]; } else if (IOS8_OR_LATER) {/ / iOS UIUserNotificationSettings * 8-10 iOS system Settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [application registerUserNotificationSettings:settings]; } else {/ / iOS 8.0 the following [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; }

/ / registered remote notifications for device token [application registerForRemoteNotifications]; } Note above:

  1. Delegate = self; delegate = self; delegate = self; #define IOS10_OR_LATER ([[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) #define IOS9_OR_LATER ([[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) #define IOS8_OR_LATER ([[UIDevice CurrentDevice] systemVersion] floatValue] >= 8.0) #define IOS7_OR_LATER ([[UIDevice currentDevice] systemVersion] FloatValue] > = 7.0)
  2. Before signing up for the push service, it was impossible to know whether the user clicked agree or disagree, and what changes the user made afterwards. Now Apple has opened up this API, and we can directly access the user’s Settings. Note that UNNotificationSettings is a read-only object and cannot be changed directly. Only through the following ways to obtain [center getNotificationSettingsWithCompletionHandler: ^ (UNNotificationSettings * _Nonnull Settings) { NSLog(@”========%@”,settings); }]; The following information is displayed: ========

    4. The method for remote push to obtain the Device Token of the Device remains unchanged. The code is as follows

#pragma mark – Obtaining device Token // Obtaining DeviceToken succeeded

  • (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

// Get the string from NSData // get the string from NSData You’ll get nil (don’t get me wrong) //NSString *string = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];

/ / correct term nsstrings * 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]:%@ “,error.description); } 5, this step is missing, this is the iOS 10 update, Apple gave us two proxy methods to handle the notification receive and click events, these two methods in the protocol, you can check.

@protocol UNUserNotificationCenterDelegate

@optional

// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification WithCompletionHandler (void (^) (UNNotificationPresentationOptions options)) completionHandler __IOS_AVAILABLE (10.0) __WATCHOS_AVAILABLE __TVOS_AVAILABLE (10.0) (3.0);

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *) response withCompletionHandler (void (^) ()) completionHandler __IOS_AVAILABLE __WATCHOS_AVAILABLE (10.0) (3.0) __TVOS_PROHIBITED;

@end

In addition, Apple combines local and remote notifications. Distinguish between local notice with remote class is UNPushNotificationTrigger h class, UNPushNotificationTrigger types are added, through which we can get some notice the trigger condition, explained as follows:

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. I’m going to do it now, and I’ll show you each one in code. Let’s return to two very agent crane method # pragma mark – iOS10 notified (local and remote) UNUserNotificationCenterDelegate / / App in front desk receive notifications

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{

UNNotificationRequest *request = notification.request; UNNotificationRequest *request = notification.request;

UNNotificationContent *content = request.content; UNNotificationContent *content = request.content;

NSDictionary *userInfo = content.userinfo;

NSNumber *badge = content.badge;

NSString *body = content.body;

UNNotificationSound *sound = content.sound;

NSString *subtitle = content.subtitle; NSString *subtitle = content.subtitle;

NSString *title = content.title;

If ([notification request. The trigger isKindOfClass: [UNPushNotificationTrigger class]]) {/ / is omitted ten thousand lines demand code… NSLog(@”iOS10 received remote notification :%@”,userInfo);

}else {// Determine local notification // omit ten thousand lines of required code…… NSLog(@”iOS10 received local notification :{\ nBody :%@,\ nTitle :%@,\ nSubTitle :%@,\ nBadge :%@,\ nSound :%@,\ nuserInfo: %@\n}”,body,title,subtitle,badge,sound,userInfo); }

// To execute this method, select whether to remind the user, Have a Badge, Sound, Alert three types can set the completionHandler (UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound| UNNotificationPresentationOptionAlert);

}

//App notification click event

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{// UNNotificationRequest *request = response.notification.request;

UNNotificationContent *content = request.content; UNNotificationContent *content = request.content;

NSDictionary *userInfo = content.userinfo;

NSNumber *badge = content.badge;

NSString *body = content.body;

UNNotificationSound *sound = content.sound;

NSString *subtitle = content.subtitle; NSString *subtitle = content.subtitle;

NSString *title = content.title;

if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { NSLog(@”iOS10 Receive remote notification :%@”,userInfo); // Omit 10,000 lines of required code here…

}else {// Determine local notification // omit ten thousand lines of required code…… NSLog(@”iOS10 received local notification :{\ nBody :%@,\ nTitle :%@,\ nSubTitle :%@,\ nBadge :%@,\ nSound :%@,\ nuserInfo: %@\n}”,body,title,subtitle,badge,sound,userInfo); } //2016-09-27 14:42:16.353978 UserNotificationsDemo[1765:800117] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called. completionHandler(); // The system requires this method to be executed}

1. The following agent method will only work when the APP is in foreground state and foreground state. It will not work in background mode

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler 2. The following proxy method will only trigger when the user clicks on the message, not when using 3DTouch, popup Action, etc. Trigger when Action is clicked!
  • (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler 3. Clicking on the agent finally requires execution: completionHandler(); // The system requires this method otherwise: 2016-09-27 14:42:16.353978 UserNotificationsDemo[1765:800117] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called. 4. Regardless of the foreground and background state. Push message banners can be displayed! Background state needless to say, the foreground needs to be set in the foreground agent method, as follows: // To execute this method, select whether to remind the user, Have a Badge, Sound, Alert three types can set the completionHandler (UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound| UNNotificationPresentationOptionAlert); 6. Compatible methods for receiving notifications before iOS 10

#pragma Mark -iOS 10 has been notified before

  • (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSLog(@”iOS6 and below, receive notification :%@”, userInfo); // Omit 10,000 lines of required code here… }
  • (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo FetchCompletionHandler :(void (^)(UIBackgroundFetchResult))completionHandler {NSLog(@”iOS7 and above, received notification :%@”, userInfo); completionHandler(UIBackgroundFetchResultNewData); // Omit 10,000 lines of required code here… } Segment: Do you think it’s over? NO, NO, NO (you think you’ve left fantasy, but you’ve just entered fantasy!) The above introduced the basic principles, basic configuration and basic method description, now done these work, our learning has just begun! Now is the time for learning and testing of push coding.

Notifications can be used in many situations in a user’s daily life, such as news notifications, scheduled meds, periodic health checks, and notifications of arrival at a certain location, all of which are interfaces in UserNotifications.

IOS 10 UserNotifications secret summary image from web.jpeg

We first learn the basic skills of simple push (climb), behind the learning of advanced custom push (walk), and finally see if we can advanced push (fly not fly up depends on the individual, I am not able to fly) :

Basic Local Notifications and Remote Notifications

Basic local push

The main process of local push generation is:

  1. Create a trigger
  2. Create the content of the push (UNMutableNotificationContent)
  3. Creating an UNNotificationRequest
  4. 1. The new function trigger can be triggered under certain conditions. Has three types: UNTimeIntervalNotificationTrigger, UNCalendarNotificationTrigger, UNLocationNotificationTrigger

1.1, UNTimeIntervalNotificationTrigger: after a period of time the trigger (push) regularly

//timeInterval: units are seconds (s) repeats: Whether circulating remind remind UNTimeIntervalNotificationTrigger after / / 50 s * trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:50 repeats:NO]; 1.2 UNCalendarNotificationTrigger: call

  • (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)repeats; Register; Time point information using NSDateComponents. (Periodically pushed)

// Remind NSDateComponents *components = [[NSDateComponents alloc] init] on Monday at 14:03; components.weekday = 2; components.hour = 16; components.minute = 3; / / components date UNCalendarNotificationTrigger * calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES]; 1.3, UNLocationNotificationTrigger: call

  • (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)repeats;

The region information uses CLCircularRegion, a subclass of CLRegion. You can configure the region property notifyOnEntry and notifyOnExit to notify when entering, exiting, or both regions. This test process is dedicated to running home from work to pay attention to the mobile phone is there push, sure enough there is (fixed push)

/ / must first import the # import < CoreLocation/CoreLocation. H >, or you’ll regin create has a problem. / / create the location information CLLocationCoordinate2D center1 = CLLocationCoordinate2DMake (39.788857, 116.5559392); CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center1 Radius :500 identifier:@” circularRegion “]; region.notifyOnEntry = YES; region.notifyOnExit = YES; It is not a duplicate / / region location information repeats (CLRegion can be location) UNLocationNotificationTrigger * locationTrigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:YES]; 2, create the content of the push (UNMutableNotificationContent)

UNNotificationContent: Property readOnly

UNMutableNotificationContent: Attributes include title, subtitle, body, badge, Sound, lauchImageName, userInfo, attachments, categoryIdentifier, threadIdentifier

Local news | | content limit size display

————-|——–|

The title | nsstrings | limit in one line, more part of ellipsis

The subtitle | nsstrings | limit in one line, more part of ellipsis

Body | nsstrings | notification bar appears, will be limited to two lines, some more ellipsis; When previewing, show them all

Printf-style escape characters in **body, such as %, need to be written as %% to display, again

/ / create notification content UNMutableNotificationContent, pay attention to not UNNotificationContent, this object is immutable objects.

UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];

Content. title = @”Dely time alert – title”;

Content.subtitle = [NSString stringWithFormat:@” -subtitle “];

It’s time for the finals of the Dely Outfit Conference. Welcome to the finals! Hope you are x-body “;

content.badge = @666;

content.sound = [UNNotificationSound defaultSound];

content.userInfo = @{@”key1″:@”value1″,@”key2″:@”value2″};

3. Create a complete local push request Demo

// Timed push

  • (void)createLocalizedUserNotification{

/ / set the trigger condition UNNotificationTrigger UNTimeIntervalNotificationTrigger * timeTrigger = [UNTimeIntervalNotificationTrigger TriggerWithTimeInterval: 5.0 f repeats: NO];

/ / create notification content UNMutableNotificationContent, pay attention to not UNNotificationContent, this object is immutable objects. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; Content. title = @”Dely time alert – title”; Content.subtitle = [NSString stringWithFormat:@” -subtitle “]; It’s time for the finals of the Dely Outfit Conference. Welcome to the finals! Hope you are x-body “; content.badge = @666; content.sound = [UNNotificationSound defaultSound]; content.userInfo = @{@”key1″:@”value1″,@”key2″:@”value2”};

NSString *requestIdentifier = @”Dely.

UNNotificationRequest Add the trigger condition and notification content to the request UNNotificationRequest * Request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:timeTrigger];

UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; / / the notification request add to UNUserNotificationCenter [center addNotificationRequest: request withCompletionHandler: ^ (NSError * _Nullable error) {if (! Error) {NSLog(@” push added successfully %@”, requestIdentifier); UIAlertController * alert = [UIAlertController alertControllerWithTitle: @ “local notification message:” @ “successfully adding push” preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction * cancelAction = [UIAlertAction actionWithTitle: @ “cancel” style: UIAlertActionStyleCancel handler: nil]; [alert addAction:cancelAction]; [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES Completion :nil]; // Omit 10,000 lines of requirements…}}]; } The result is as follows:

IOS 10 UserNotifications summary installs X final notifications. JPG

2. Basic remote push

If you want to emulate remote push, you can emulate the basic remote push on the remote side by configuring the basic environment, certificates, push switches, and basic methods I described earlier.

1. After running the project, you will get the Device Token of the Device, which will be used later.

Device token.png in iOS 10 UserNotifications

2. Now we need a push server to send information to APNS. As I said earlier, I bought an APNS Pusher for $12 to simulate the remote push service. Of course, you can use it for free, such as:

NWPusher

APNS pusher is a summary of iOS 10 UserNotifications cheats

3, you need to put the device token you just obtained in the corresponding position, and you need to configure the Push certificate.

4, Need to add aps content, then click Send OK

{“aps” : {“alert” : {“title” : “iOS remote message, I am the main title! -title”, “subtitle” : “iOS remote message, I am the main title! -subtitle “, “body” : “Dely,why am I so handsome -body”}, “badge” : “2”}

IOS 10 UserNotifications secret summary of remote messages.jpg

6, Notification Management

Check, modify and delete the push. Both require a required parameter, requestIdentifier

1. Update notifications

The Local Notification needs to update the Request. The same requestIdentifier can be added to the push center again. In other words, the local Notification Request is created again (as long as the requestIdentifier is ok). The application scenario is shown in the figure

IOS 10 UserNotifications Secret summary Local Notification updated. PNG

Remote Notification updates need to be uniquely identified by the new field apps-collapsor-id, which is not currently supported by APNS Pusher, but there are a number of tools available on Github:

Github.com/KnuffApp/Kn…

So remote can also update push messages

2. Search and delete push messages

// Notification requests that are waiting for their trigger to fire

  • (void)getPendingNotificationRequestsWithCompletionHandler:(void(^)(NSArray

    *requests))completionHandler; // Delete all undelivered messages with a specific ID
  • (void)removePendingNotificationRequestsWithIdentifiers:(NSArray

    *)identifiers; // Delete all undelivered messages
  • (void)removeAllPendingNotificationRequests; // Notifications that have been delivered and remain in Notification Center. Notifiations triggered by location cannot The spectrum is retrieved, but can be removed
  • (void)getDeliveredNotificationsWithCompletionHandler:(void(^)(NSArray

    *notifications))completionHandler __TVOS_PROHIBITED; // Delete all messages that have been delivered with a specific ID
  • (void)removeDeliveredNotificationsWithIdentifiers:(NSArray

    *)identifiers __TVOS_PROHIBITED; // Delete all delivered messages
  • (void)removeAllDeliveredNotifications __TVOS_PROHIBITED; The tests are as follows:
  • (void)notificationAction{ NSString requestIdentifier = @”Dely.X.time”; UNUserNotificationCenter center = [UNUserNotificationCenter currentNotificationCenter];

/ / remove devices have received all messages to push / / [center removeAllDeliveredNotifications];

/ / remove devices have received specific id all messages to push / / [center removeDeliveredNotificationsWithIdentifiers: @ [requestIdentifier]].

/ / access devices have received the news of the push [center getDeliveredNotificationsWithCompletionHandler: ^ (NSArray < > UNNotification * * _Nonnull notifications) { }]; When you receive a notification, you need to handle your request logic in the delegate method in the AppDelegate. You need to write this yourself. So far you’ve mastered basic local push and basic remote push!

It’s all TM crap, and it’s all local and remote Attachments (Media Attachments, Notification Actions, custom push interface, etc.) that you’re going to start writing. Save it for your next blog post to share.

Welcome to add Java exchange QQ group: 668041364 exchange experience