Written in the book of the former
In iOS 10, the previously cluttered apis for Remote Notification and Local Notification have been refactored and new functionality has been extended on top of iOS 8 and iOS 9. Introduced a new and independent UserNotifications. Various API framework to centrally manage related notice.
Compared with developers, it is easier to use. Compared with operation, the new framework has Attachment and custom UI and other new functions, so it has a more flexible way to deal with relevant notifications.
Interface analysis
Above for new UserNotifications. Framework bring us various interfaces.
1.
There is only one method in a class
// Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
+ (NSString *)localizedUserNotificationStringForKey:(NSString *)key arguments:(nullable NSArray *)arguments __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;Copy the code
The main function is to provide a localized string at the time the notification is rendered.
2.
There is only one attribute, UNErrorDomain, and an enumeration, UNErrorCode, which as the name implies is the value of the error attribute.
3.
Has two properties
// The date displayed on the notification.
@property (nonatomic, readonly, copy) NSDate *date;
// The notification request that caused the notification to be delivered.
@property (nonatomic, readonly, copy) UNNotificationRequest *request;Copy the code
Typically as the returned message instance.
4.
As can be seen from the name, the function of the class is to define some Action actions after receiving notification, including identifier, title, and options. Options is an enumerated type
typedef NS_OPTIONS(NSUInteger, UNNotificationActionOptions) {/ / been this action should require unlocking before being performed. / / button to red, Points need to unlock the screen display UNNotificationActionOptionAuthenticationRequired = (1 < < 0), // Whether this action should be indicated as destructive // Button is black, Click will not enter the App UNNotificationActionOptionDestructive = (1 < < 1), // Whether this action should cause the application to launch in the foreground. Click to enter the App UNNotificationActionOptionForeground = (1 < < 2), __TVOS_PROHIBITED __WATCHOS_AVAILABLE} __IOS_AVAILABLE (10.0) (3.0);Copy the code
With a subclass UNTextInputNotificationAction, so-called similar reply WeChat and called iMessage — when used.
5.
The notification attachment property class, which has three main properties
// The identifier of this attachment @property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *identifier; // The URL to the attachment's data. If you have obtained this attachment from UNUserNotificationCenter then the URL @property (nonatomic, readonly, copy) NSURL *URL; // The UTI of the attachment. @property (nonatomic, readonly, copy) NSString *type;Copy the code
There are four constants
// Key to manually provide a type hint for the attachment. If not set the type hint will be guessed from the Attachment's file extension. Value must be an NSString. If no type hint is set, the type will be guessed from the attachment file extension. The value must be an NSString format. __WATCHOS_AVAILABLE extern nsstrings * const UNNotificationAttachmentOptionsTypeHintKey __IOS_AVAILABLE (10.0) (3.0); // Key to specify if the thumbnail for this attachment is hidden. Defaults to NO. Value must be a boolean NSNumber. // Note that this attachment thumbnail is a hidden key. The default value is NO. The value must be a Boolean of type NSNumber. Extern nsstrings * const UNNotificationAttachmentOptionsThumbnailHiddenKey __IOS_AVAILABLE (10.0) __WATCHOS_AVAILABLE (3.0); // Key to specify a normalized clipping rectangle to use for the attachment thumbnail. Value must be a CGRect encoded Specify a standardized using CGRectCreateDictionaryRepresentation. / / clipping rectangle thumbnail keys used for accessories. The value must be a CGRect value encoded using DictionaryRepresentation. Extern nsstrings * const UNNotificationAttachmentOptionsThumbnailClippingRectKey __IOS_AVAILABLE (10.0) __WATCHOS_AVAILABLE (3.0); // Key to specify the animated image frame number or the movie time to use as the thumbnail. // An animated image frame number must be an NSNumber. A movie time must either be an NSNumber with the time in seconds or a CMTime encoded using CMTimeCopyAsDictionary. // Specifies the number of frames for the animated image or the time of the movie with the thumbnail. // The frame number of the animated image must be an NSNumber object. The time of the movie must be the time in seconds of an NSNumber object or the CMTime value encoded using the CMTimeCopyAsDictionary. __WATCHOS_AVAILABLE extern nsstrings * const UNNotificationAttachmentOptionsThumbnailTimeKey __IOS_AVAILABLE (10.0) (3.0);Copy the code
6.
The class used to store actions
// The unique identifier for this category. The UNNotificationCategory's actions will be displayed on notifications when the UNNotificationCategory's identifier matches the UNNotificationRequest's categoryIdentifier. @property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *identifier; // The UNNotificationActions in The order they will be displayed. readonly, copy) NSArray *actions; // The intents supported support for notifications of this category. See for possible values. @property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray *intentIdentifiers; @property (NS_NONATOMIC_IOSONLY, readonly) UNNotificationCategoryOptions options;Copy the code
Options is an enumerated value of permissions, which can be used together
typedef NS_OPTIONS(NSUInteger, UNNotificationCategoryOptions) { UNNotificationCategoryOptionNone = (0), // Whether dismiss action should be sent to the UNUserNotificationCenter delegate UNNotificationCategoryOptionCustomDismissAction = (1 << 0), // Whether notifications of this category should be allowed in CarPlay UNNotificationCategoryOptionAllowInCarPlay = (2 << 0),} __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;Copy the code
7.
Think of it simply as a Model class that stores all notifications, including attachments, sounds, titles, and userInfo.
Have a subclass UNMutableNotificationContent, and the difference can be seen from the name of the parent can be modified, a property is less than the parent class in a readonly attribute.
8.
There are three properties, identifier, message Model, and NotificationTrigger.
// The unique identifier for this notification request. It can be used to replace or remove a pending notification request or a delivered notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *identifier;
// The content that will be shown on the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) UNNotificationContent *content;
// The trigger that will or did cause the notification to be delivered. No trigger means deliver now.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) UNNotificationTrigger *trigger;Copy the code
9.
As you can see by name, request is used as the corresponding notification Action. The user can get the content of the entire notification and the identifier corresponding to the action.
// The notification to which the user responded. @property (NS_NONATOMIC_IOSONLY, readonly, copy) UNNotification *notification; // The action identifier that the user chose: // * UNNotificationDismissActionIdentifier if the user dismissed the notification // * UNNotificationDefaultActionIdentifier if the user opened the application from the notification // * the identifier for a registered UNNotificationAction for other actions @property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *actionIdentifier;Copy the code
Subclasses UNTextInputNotificationResponse also contains userText, can take to the contents of user input.
10.
It’s basically a set of properties for notifications, and for properties, there are three enumerated values
typedef NS_ENUM(NSInteger, UNAuthorizationStatus) { // The user has not yet made a choice regarding whether the application may post user notifications. UNAuthorizationStatusNotDetermined = 0, // The application is not authorized to post user notifications. UNAuthorizationStatusDenied, / / The application is authorized to post a user notifications. UNAuthorizationStatusAuthorized} __IOS_AVAILABLE (10.0) __WATCHOS_AVAILABLE __TVOS_AVAILABLE (10.0) (3.0); typedef NS_ENUM(NSInteger, UNNotificationSetting) { // The application does not support this notification type UNNotificationSettingNotSupported = 0, // The notification setting is turned off. UNNotificationSettingDisabled, // The notification setting is turned on. UNNotificationSettingEnabled, __WATCHOS_AVAILABLE __TVOS_AVAILABLE} __IOS_AVAILABLE (10.0) (10.0) (3.0); typedef NS_ENUM(NSInteger, UNAlertStyle) { UNAlertStyleNone = 0, UNAlertStyleBanner, UNAlertStyleAlert, } __IOS_AVAILABLE (10.0) __TVOS_PROHIBITED __WATCHOS_PROHIBITED;Copy the code
11.
Two methods, one is set to the default tone, the other is set to the custom tone. You can use the name of the sound directly instead of the file path.
// The default sound used for notifications.
+ (instancetype)defaultSound;
// The name of a sound file to be played for the notification. The sound file must be contained in the app’s bundle or in the Library/Sounds folder of the app's data container. If files exist in both locations then the file in ~/Library/Sounds will be preferred.
+ (instancetype)soundNamed:(NSString *)name __WATCHOS_PROHIBITED;Copy the code
12.
NotificationTrigger is an important new function. The four methods provide more options for App application. Calendar and geographical location are the new Trigger.
So, there are four subclasses of this class: push notification trigger, time notification trigger, calendar notification trigger, and locale notification trigger. In contrast, subclasses have their own starting properties.
13.
The reason why USNotificationCenter and USNotificationCenter think this way is almost confusing at first glance.
The most important class, notification registration, activation, edit, delete functions are done by this class. Through [UNUserNotificationCenter currentNotificationCenter] singleton method.
14.
There are two methods called when a notified request is received and when the system is about to destroy it.
15.
. This class is not UserNotifications framework, is mainly used as modification notification display UI, need to be added when using UserNotificationsUI) framework. More on this later.
Notification Extension
Starting with Share Extensions and the like, iOS has gradually supported extensions that leverage sandboxes and the like. In iOS 10, notifications are related to two things: Service Extension and Content Extension. The former gives us the opportunity to customize the notification content after receiving it remotely and before displaying it. The latter can be used to customize the UI style of the notification view.
Deprecated apis in iOS 10
- UILocalNotification
- UIMutableUserNotificationAction
- UIMutableUserNotificationCategory
- UIUserNotificationAction
- UIUserNotificationCategory
- UIUserNotificationSettings
- handleActionWithIdentifier:forLocalNotification:
- handleActionWithIdentifier:forRemoteNotification:
- didReceiveLocalNotification:withCompletion:
- didReceiveRemoteNotification:withCompletion:
Demo
Demo address: github.com/derekhuangx…
Since iOS 10 has changed the restrictions on obtaining permissions, as an adaptation, you are expected to change the fields related to obtaining permissions in the info.plist file.
1. Text notice
Text notification is relatively simple, only need to create UNMutableNotificationContent entity class, create UNTimeIntervalNotificationTrigger entity class, and then added to the single case, notify the center then trigger.
- (IBAction)btnCreateWordNotofication:(id)sender { UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc]init]; content.title = @"NotificationCenter"; content.subtitle = @"testWord"; Content.body = @" Local notification test "; UNTimeIntervalNotificationTrigger * triger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; NSString * requestIdentifier = @"request"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:triger]; [[UNUserNotificationCenter currentNotificationCenter]addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }]; }Copy the code
2. Picture notification
Similar to pure text notification, but need additional UNNotificationAttachment attribute is added in the UNMutableNotificationContent, the remaining basic similar. Note that Content.attachments is an array.
- (IBAction)btnCreatePictrueNotofication:(id)sender { UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc]init]; content.title = @"NotificationCenter"; content.subtitle = @"testWord"; Content.body = @" Local notification test "; NSString * imagePath = [[NSBundle mainBundle]pathForResource:@"Notification_Image" ofType:@"png"]; if (imagePath) { UNNotificationAttachment * imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"imagePath"Copy the code
URL:[NSURL fileURLWithPath:imagePath] options:nil error:nil]; if (imageAttachment) { content.attachments = @[imageAttachment]; }}
UNTimeIntervalNotificationTrigger * triger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
NSString * requestIdentifier = @"request";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:triger];
[[UNUserNotificationCenter currentNotificationCenter]addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
}Copy the code
3. Video notification
The methods of video notification and picture notification are the same, but in the Demo, I added three actions to the method of video notification, which can be added to the singleton of the notification center. The specific methods and functions have been introduced above.
- (IBAction)btnCreateVideoNotofication:(id)sender { UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc]init]; content.title = @"NotificationCenter"; content.subtitle = @"testWord"; Content.body = @" Local notification test "; NSString * videoPath = [[NSBundle mainBundle]pathForResource:@"Notification_video" ofType:@"mp4"]; if (videoPath) { UNNotificationAttachment * videoAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"videoPath" URL:[NSURL fileURLWithPath:videoPath] options:nil error:nil]; if (videoAttachment) { content.attachments = @[videoAttachment]; } } NSMutableArray * actionArr = [NSMutableArray array]; UNNotificationAction * actionA = [UNNotificationAction actionWithIdentifier:@"IdentifierUnlock" title:@" Enter application" options:UNNotificationActionOptionForeground]; UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"IdentifierRed" title:@"Another Action" options:UNNotificationActionOptionDestructive]; UNNotificationAction * actionC = [UNNotificationAction actionWithIdentifier:@"IdentifierBlack" title:@"Third Action" options:UNNotificationActionOptionAuthenticationRequired]; [actionArr addObjectsFromArray:@[actionA, actionB, actionC]]; if (actionArr.count > 0) { UNNotificationCategory * categoryNotification = [UNNotificationCategory categoryWithIdentifier:@"categoryOperationAction" actions:actionArr intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; [[UNUserNotificationCenter currentNotificationCenter]setNotificationCategories:[NSSet setWithObject:categoryNotification]]; content.categoryIdentifier = @"categoryOperationAction"; } UNTimeIntervalNotificationTrigger * triger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; NSString * requestIdentifier = @"request"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:triger]; [[UNUserNotificationCenter currentNotificationCenter]addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }]; }Copy the code
The last
This article mainly introduces the use of THE API, writing a simple Demo of local trigger notifications, and then focusing on remote push multimedia notifications and custom UI notifications.
On the other
Before Apple Watch, new widgets and UserNotifications behind. The framework, Apple seems to be very hard to extricate the attention of our immersed in a mobile phone, We tried to avoid the possibility that we would have to open the App because of notifications and short actions.
I wonder if this is Apple’s new definition of what it means to use a phone.
reference
- Onevcat.com/2016/08/not…
- www.jianshu.com/p/9b720efe3…
- www.cnblogs.com/dsxniubilit…
- Developer.apple.com/videos/play…
- Developer.apple.com/videos/play…