Recently in the study of IOS10 on the new features of the push, compared with the previous did a great change, summed up mainly the following points:
- Push content richer, from the previous alert to the present title, subtitle, Body
- Push unification triggered by trigger
- Add attachments, slices, audio, and video for push, which makes pushing content more colorful
- Easy to update push content
Import New Frame
Add a new frame usernotifications.framework
#import <UserNotifications/UserNotifications.h>
Register push
When setting up notifications, advanced line registration is required to obtain authorization
IOS10 all notifications are managed through Unusernotificationcenter, including remote notifications and local notifications
//iOS8以下 [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; //iOS8 - iOS10 [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]]; //iOS10 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }
Get user settings
IOS10 provides an interface for obtaining user authorization-related Settings Getnotificationsettingswithcompletionhandler:, callback with a Unnotificationsettings object, which has the following properties, Accurate access to various licensing information
authorizationStatussoundSetting badgeSetting alertSetting notificationCenterSetting lockScreenSetting carPlaySettingalertStyle
Like the following method, click Allow
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { //点击允许 NSLog(@"注册通知成功"); [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { NSLog(@"%@", settings); }]; } else { //点击不允许 NSLog(@"注册通知失败"); } }];打印信息: *<UNNotificationSettings: 0x174090a90; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, alertSetting: NotSupported, carPlaySetting: Enabled, alertStyle: Banner>*
Sign up for APNs, get token
IOS10, the way to register APNs and get tokens is the same as before.
In application:didfinishlaunchingwithoptions: Call the Registerforremotenotifications method
[[UIApplication sharedApplication] registerForRemoteNotifications];
Get token in Proxy method Application:didregisterforremotenotificationswithdevicetoken:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0){ NSLog(@"deviceToken:%@",deviceToken); }- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){ NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error); }
Set the action and category for handling notifications
Before iOS8, there is no category this attribute;
in iOS8 registration push, get authorization, you can set the category together, the method of registration directly with this parameter;
in IOS10, You need to call a method setnotificationcategories: To set the category for the Unusernotificationcenter instance that manages the push, and the category to set the action;
Setting category//unnotificationactionoptionauthenticationrequired needs to be unlocked//unnotificationactionoptiondestructive shown in red Unnotificationactionoptionforeground Click to open appunnotificationaction *action1 = [unnotificationaction actionwithidentifier:@ "Action1" title:@ "strategy 1 Behavior 1" options:unnotificationactionoptionforeground]; Untextinputnotificationaction *action2 = [untextinputnotificationaction actionwithidentifier:@ "Action2" title:@ " Strategy 1 Behavior 2 "options:unnotificationactionoptiondestructive textinputbuttontitle:@" comment "textinputplaceholder:@" Reply "]; Unnotificationcategoryoptionnone//unnotificationcategoryoptioncustomdismissaction Clear Notification is triggered by the proxy method that will walk the notification// Unnotificationcategoryoptionallowincarplay for driving mode unnotificationcategory *category1 = [Unnotificationcategory categ orywithidentifier:@ "Category1" Actions:@[action2,action1] minimalactions:@[action2,action1] intentIdentifiers:@[] Options:unnotificationcategoryoptioncustomdismissaction]; Unnotificationaction *action3 = [Unnotificationaction actionwithidentifier:@ "Action3" title:@ "strategy 2 behavior 1" options:unnotificationactionoptionforeground]; Unnotificationaction *action4 = [unnotificationaction actionwithidentifier:@ "Action4" title:@ "strategy 2 Behavior 2" options: Unnotificationactionoptionforeground]; Unnotificationcategory *category2 = [unnotificationcategory categorywithidentifier:@ "Category2" Actions:@[action3, Action4] minimalactions:@[action3,action4] intentidentifiers:@[] Options: Unnotificationcategoryoptioncustomdismissaction]; [[Unusernotificationcenter Currentnotificationcenter] Setnotificationcategories:[nsset setWithObjects:category1, Category2, Nil]];
Set notification content
Because the IOS10 remote notification is unified with local notifications, the notification content property is consistent, but remote push needs to be payload in the specific settings, the following local notification as an example, to introduce the content of Unnotificationcontent
The official website clearly stated that we are not able to directly create unnotificationcontent instances, if we need to configure the content of the various properties, we need to use the Unmutablenotificationcontent
Take a look at some of its properties:
Attachments//Accessories badge//Logo body//push content Bodycategoryidentifier//category logo launchim Agename//Click Notifications to enter the app's startup diagram sound//Voice subtitle//push content subtitle title//push content title UserInfo Remote notification content Unmutablenotificationcontent *content = [[Unmutablenotificationcontent alloc] init]; Content.title = @ "Test"; Content.subtitle = @ "1234567890"; Content.body = @ "copyright©2016 year Jpush. All rights reserved. "; Content.badge = @1; Nserror *error = nil; NSString *path = [[NSBundle mainbundle] pathforresource:@ "718835727" oftype:@ "PNG"]; Unnotificationattachment *att = [unnotificationattachment attachmentwithidentifier:@ "ATT1" URL:[NSURL Fileurlwithpath:path] Options:nil error:&error]; if (Error) {NSLog (@ "Attachment error%@", error); } content.attachments = @[att]; Content.categoryidentifier = @ "Category1"; Here the Category1 is set, which corresponds to the category previously set content.launchimagename = @ "1-eb_0ovtcxjxhz7-ioObsaq "; Unnotificationsound *sound = [Unnotificationsound defaultsound];content.sound = sound;
Notification triggers
Unnotificationtrigger
There are 4 types of IOS 10 triggers
- Unpushnotificationtrigger triggers the APNs service, the system is set up automatically (this is the identity that distinguishes between local and remote notifications)
- Untimeintervalnotificationtrigger triggered after some time
- Uncalendarnotificationtrigger Specified date Trigger
-
Unlocationnotificationtrigger is triggered by position, supports access to a place, or leaves somewhere or has
//十秒后UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];//每周日早上8:00NSDateComponents *component = [[NSDateComponents alloc] init];component.weekday = 1;component.hour = 8;UNCalendarNotificationTrigger *trigger2 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:component repeats:YES];//圆形区域,进入时候进行通知CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(80.335400, -90.009201);CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:cen radius:500.0 identifier:@“center"];region.notifyOnEntry = YES; //进入的时候region.notifyOnExit = NO; //出去的时候UNLocationNotificationTrigger *trigger3 = [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO];
Add Notification/Update notifications
- Create an instance of the Unnotificationrequest class, be sure to set the identifier for it, in the back of the Find, update, delete notification, this identifier is used to distinguish this notification from other notifications
- Add the request to Unusernotificationcenter and set the trigger to wait for the trigger
-
If another request has the same identity as the previous request, different content can be used to achieve the purpose of the update notification
NSString *requestIdentifer = @"TestRequest"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger1]; //把通知加到UNUserNotificationCenter, 到指定触发点会被触发 [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }]; //在另外需要更新通知的地方UNMutableNotificationContent *newContent = [[UNMutableNotificationContent alloc] init];newContent.title = @"Update";newContent.subtitle = @"XXXXXXXXX";newContent.body = @"Copyright © 2016年 jpush. All rights reserved.";UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"TestRequest" content:newContent trigger:trigger1];[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {}];
Get and delete notifications
There are two states of notice here
- Pending waiting for a trigger notification
-
Delivered has been triggered to show notifications in notification hubs
//获取未触发的通知[[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) { NSLog(@"pending: %@", requests);}];//获取通知中心列表的通知[[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) { NSLog(@"Delivered: %@", notifications);}]; //清除某一个未触发的通知 [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[@"TestRequest1"]]; //清除某一个通知中心的通知 [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[@"TestRequest2"]]; //对应的删除所有通知[[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];[[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
Delegate
<UNUserNotificationCenterDelegate>
IOS10 receive notification is no longer in application:didreceiveremotenotification: method to deal with, IOS10 launch new proxy method, receive and process all kinds of notifications (local or remote)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { //应用在前台收到通知 NSLog(@"========%@", notification);}- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { //点击通知进入应用 NSLog(@"response:%@", response);}
At last
The next article continues to introduce the rich media push unnotificationserviceextension and Notification content extension, not to be continued ...
Thanks for sharing
IOS10 about push-B