前言
上一篇文章介紹了UILocalNotification
的使用尖飞,這篇文章主要介紹一下UNUserNotificationCenter
的使用砾嫉。UILocalNotification
現(xiàn)在雖然還能使用陋守,但是也已經(jīng)是要被廢棄不用的方法了式撼,而本篇所要介紹的UNUserNotificationCenter
就是被棄用方法的替代品终抽。
UNUserNotificationCenter的使用
還是那個思路纪他,只知道使用UNUserNotificationCenter
來實(shí)現(xiàn)本地推送易猫,具體怎么實(shí)現(xiàn)不知道耻煤。
我們在上一篇文章中所敘述的代碼在Xcode里雖然能執(zhí)行,但是由于那時蘋果棄用的方法准颓,所以會報(bào)出一大堆惡心的警告哈蝇,我們就來看一下警告,就能夠從中知道該怎么使用UNUserNotificationCenter
了攘已。
1. 注冊通知
關(guān)于注冊通知的這個方法中對于警告的類我都在圖中標(biāo)注了炮赦,警告的意思就是說某某方法已經(jīng)被棄用,讓使用UserNotifications
框架中的某某方法代替样勃。那么我們就用新的類來注冊一下通知吠勘。(既然是新的框架,必然要引入頭文件咯峡眶,不然是會報(bào)錯的喲)
上圖中出現(xiàn)了UNUserNotificationCenter
新類和-[UNUserNotificationCenter requestAuthorizationWithOptions:completionHandler:]
剧防、-[UNUserNotificationCenter setNotificationCategories:]
兩個示例方法,先查看一下新類的構(gòu)造辫樱。
@interface UNUserNotificationCenter : NSObject
// The delegate can only be set from an application
@property (NS_NONATOMIC_IOSONLY, nullable, weak) id <UNUserNotificationCenterDelegate> delegate;
// Returns YES if the current device supports content extensions
@property (NS_NONATOMIC_IOSONLY, readonly) BOOL supportsContentExtensions;
// The UNUserNotificationCenter for the current application
+ (UNUserNotificationCenter *)currentNotificationCenter;
- (instancetype)init NS_UNAVAILABLE;
// User authorization is required for applications to notify the user using UNUserNotificationCenter via both local and remote notifications.
- (void)requestAuthorizationWithOptions:(UNAuthorizationOptions)options completionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler;
// Notification categories can be used to choose which actions will be displayed on which notifications.
- (void)setNotificationCategories:(NSSet<UNNotificationCategory *> *)categories __TVOS_PROHIBITED;
- (void)getNotificationCategoriesWithCompletionHandler:(void(^)(NSSet<UNNotificationCategory *> *categories))completionHandler __TVOS_PROHIBITED;
// The application's user notification settings
- (void)getNotificationSettingsWithCompletionHandler:(void(^)(UNNotificationSettings *settings))completionHandler;
// Notification requests can be scheduled to notify the user via time and location. See UNNotificationTrigger for more information. Calling -addNotificationRequest: will replace an existing notification request with the same identifier. A notification request with the identifier as an existing delivered notifications will alert for the new notification request and replace the existing delivered notification when it is triggered. The number of pending notification requests that may be scheduled by an application at any one time is limited by the system.
- (void)addNotificationRequest:(UNNotificationRequest *)request withCompletionHandler:(nullable void(^)(NSError *__nullable error))completionHandler;
// Notification requests that are waiting for their trigger to fire
- (void)getPendingNotificationRequestsWithCompletionHandler:(void(^)(NSArray<UNNotificationRequest *> *requests))completionHandler;
- (void)removePendingNotificationRequestsWithIdentifiers:(NSArray<NSString *> *)identifiers;
- (void)removeAllPendingNotificationRequests;
// Notifications that have been delivered and remain in Notification Center. Notifiations triggered by location cannot be retrieved, but can be removed.
- (void)getDeliveredNotificationsWithCompletionHandler:(void(^)(NSArray<UNNotification *> *notifications))completionHandler __TVOS_PROHIBITED;
- (void)removeDeliveredNotificationsWithIdentifiers:(NSArray<NSString *> *)identifiers __TVOS_PROHIBITED;
- (void)removeAllDeliveredNotifications __TVOS_PROHIBITED;
@end
從以上的構(gòu)造中我們可以知道的是峭拘,UNUserNotificationCenter
類繼承自NSObject
類,還有一個UNUserNotificationCenterDelegate
類型的代理狮暑,一個類方法+ (UNUserNotificationCenter *)currentNotificationCenter;
用于返回當(dāng)前應(yīng)用的通知中心鸡挠;至于下面的那么多示例方法,其中包括注冊通知的方法搬男、設(shè)置categories
的方法拣展、獲取通知的設(shè)置的方法、添加通知的方法止后、移除通知的方法等等瞎惫。
因?yàn)槲覀兪且酝ㄖ氏茸屑?xì)看一下注冊通知這個方法译株。
- (void)requestAuthorizationWithOptions:(UNAuthorizationOptions)options completionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler;
該方法需要一個UNAuthorizationOptions
類型的參數(shù)瓜喇,點(diǎn)進(jìn)去看一下這個類型,發(fā)現(xiàn)這個竟然是個枚舉類型的歉糜,跟上篇文章中設(shè)置通知方法中的那個參數(shù)類似乘寒,只是換了一個名稱而已。至于后面的blockcompletionHandler
匪补,就是注冊結(jié)果的一個block伞辛。
typedef NS_OPTIONS(NSUInteger, UNAuthorizationOptions) {
UNAuthorizationOptionBadge = (1 << 0),
UNAuthorizationOptionSound = (1 << 1),
UNAuthorizationOptionAlert = (1 << 2),
UNAuthorizationOptionCarPlay = (1 << 3),
} __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
接下來我們就可以順利的寫出來注冊通知的代碼了烂翰,如下:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
這里還有個代理忘了說了,center
的代理方法有兩個蚤氏,如下:
@protocol UNUserNotificationCenterDelegate <NSObject>
@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) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(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 application:didFinishLaunchingWithOptions:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;
@end
這個代理方法可以根據(jù)項(xiàng)目實(shí)際需求看是否需要了甘耿。
2. 設(shè)置通知
還是老路子,先來看一下發(fā)送通知的報(bào)黃警告內(nèi)容竿滨。
警告的內(nèi)容明確說了- scheduleLocalNotification:
這個方法被棄用了佳恬,要讓使用-[UNUserNotificationCenter addNotificationRequest:withCompletionHandler:]
來代替,這么一看于游,這不就是剛才注冊通知時候的那個UNUserNotificationCenter
類中的示例方法嘛毁葱,這下問題就更好解決了,方法所在類都了解了贰剥,剩余的就是看參數(shù)咯倾剿。
- (void)addNotificationRequest:(UNNotificationRequest *)request withCompletionHandler:(nullable void(^)(NSError *__nullable error))completionHandler;
從上面的函數(shù)中我們可以知道,該實(shí)例方法需要一個UNNotificationRequest
類型的參數(shù)蚌成。點(diǎn)進(jìn)去看看它究竟是個什么鬼前痘。
@interface UNNotificationRequest : NSObject <NSCopying, NSSecureCoding>
// 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;
+ (instancetype)requestWithIdentifier:(NSString *)identifier content:(UNNotificationContent *)content trigger:(nullable UNNotificationTrigger *)trigger;
- (instancetype)init NS_UNAVAILABLE;
@end
進(jìn)去一看,哇塞担忧,這么簡短际度,只有短短的三十行代碼(包含注釋),知道了這個類是集成自NSObject
類涵妥,還有三個成員變量和一個類方法的初始方法和一個示例方法的初始化方法。我們在初始化的時候肯定就用類方法初始化啊坡锡,這樣更簡單蓬网,因?yàn)樵陬惙椒ㄖ幸呀?jīng)把必須的參數(shù)都給包含了,不用使用- init
方法之后再依次的給其成員變量賦值鹉勒。
- 類方法
+ (instancetype)requestWithIdentifier:(NSString *)identifier content:(UNNotificationContent *)content trigger:(nullable UNNotificationTrigger *)trigger;
這個方法中除了需要一個字符串的標(biāo)識符identifier
以外帆锋,還需要UNNotificationContent
類型的content以及UNNotificationTrigger
類型的trigger。接下來我們就來仔細(xì)看一下這兩個參數(shù)禽额。
A. UNNotificationContent
類型的content
先來看一下類組成
@interface UNNotificationContent : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>
// Optional array of attachments.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray <UNNotificationAttachment *> *attachments __TVOS_PROHIBITED;
// The application badge number.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) NSNumber *badge;
// The body of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *body __TVOS_PROHIBITED;
// The identifier for a registered UNNotificationCategory that will be used to determine the appropriate actions to display for the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *categoryIdentifier __TVOS_PROHIBITED;
// The launch image that will be used when the app is opened from the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *launchImageName __TVOS_PROHIBITED;
// The sound that will be played for the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) UNNotificationSound *sound __TVOS_PROHIBITED;
// The subtitle of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *subtitle __TVOS_PROHIBITED;
// The unique identifier for the thread or conversation related to this notification request. It will be used to visually group notifications together.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *threadIdentifier __TVOS_PROHIBITED;
// The title of the notification.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *title __TVOS_PROHIBITED;
// Apps can set the userInfo for locally scheduled notification requests. The contents of the push payload will be set as the userInfo for remote notifications.
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDictionary *userInfo __TVOS_PROHIBITED;
@end
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNMutableNotificationContent : UNNotificationContent
// Optional array of attachments.
@property (NS_NONATOMIC_IOSONLY, copy) NSArray <UNNotificationAttachment *> *attachments __TVOS_PROHIBITED;
// The application badge number. nil means no change. 0 to hide.
@property (NS_NONATOMIC_IOSONLY, copy, nullable) NSNumber *badge;
// The body of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *body __TVOS_PROHIBITED;
// The identifier for a registered UNNotificationCategory that will be used to determine the appropriate actions to display for the notification.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *categoryIdentifier __TVOS_PROHIBITED;
// The launch image that will be used when the app is opened from the notification.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *launchImageName __TVOS_PROHIBITED;
// The sound that will be played for the notification.
@property (NS_NONATOMIC_IOSONLY, copy, nullable) UNNotificationSound *sound __TVOS_PROHIBITED;
// The subtitle of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *subtitle __TVOS_PROHIBITED;
// The unique identifier for the thread or conversation related to this notification request. It will be used to visually group notifications together.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *threadIdentifier __TVOS_PROHIBITED;
// The title of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
@property (NS_NONATOMIC_IOSONLY, copy) NSString *title __TVOS_PROHIBITED;
// Apps can set the userInfo for locally scheduled notification requests. The contents of the push payload will be set as the userInfo for remote notifications.
@property (NS_NONATOMIC_IOSONLY, copy) NSDictionary *userInfo;
@end
這個是代碼量相比較上一個類是多了很多锯厢,但是再仔細(xì)看一下,這是兩個類脯倒,第一個類UNNotificationContent
是繼承自NSObject
類实辑,第二個類 UNMutableNotificationContent
繼承自UNNotificationContent
,有沒有很熟悉的感覺藻丢,這不就是跟NSArray
和NSMutableArray
的關(guān)系一樣嘛剪撬,仔細(xì)看一下成員變量都基本上相同,唯一的區(qū)別在于前者的成員變量的是readonly
的悠反,后者則沒有限制残黑,那么我們要構(gòu)造這個參數(shù)就可以直接使用后者可變的UNMutableNotificationContent
來構(gòu)造了馍佑。至于成員變量無非就是設(shè)置推送內(nèi)容、聲音梨水、圖片等的拭荤,唯一值得一提的是,這里的聲音又單獨(dú)封裝了一個類UNNotificationSound
來實(shí)現(xiàn)疫诽,其中包含有一個默認(rèn)聲音的+ (instancetype)defaultSound;
類方法和可以自定義聲音+ (instancetype)soundNamed:(NSString *)name __WATCHOS_PROHIBITED;
類方法以及一個- init
初始化方法舅世。至于使用那就不用多說了吧。
B. UNNotificationTrigger
類型的trigger
先來看一下類構(gòu)造
@interface UNNotificationTrigger : NSObject <NSCopying, NSSecureCoding>
@property (NS_NONATOMIC_IOSONLY, readonly) BOOL repeats;
- (instancetype)init NS_UNAVAILABLE;
@end
// UNPushNotificationTrigger can be sent from a server using Apple Push Notification Service.
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNPushNotificationTrigger : UNNotificationTrigger
@end
// UNTimeIntervalNotificationTrigger can be scheduled on the device to notify after the time interval, and optionally repeat.
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNTimeIntervalNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly) NSTimeInterval timeInterval;
+ (instancetype)triggerWithTimeInterval:(NSTimeInterval)timeInterval repeats:(BOOL)repeats;
- (nullable NSDate *)nextTriggerDate;
@end
// UNCalendarNotificationTrigger can be scheduled on the device to notify based on date and time values, and optionally repeat. For example, if a notification should be delivered at the next 8:00 AM then set the 'hour' property of dateComponents to 8. If the notification should be delivered every day at 8:00 AM then set repeats to YES.
__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNCalendarNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDateComponents *dateComponents;
// The next date is calculated using matching date components.
+ (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)repeats;
- (nullable NSDate *)nextTriggerDate;
@end
// UNLocationNotificationTrigger can be scheduled on the device to notify when the user enters or leaves a geographic region. The identifier on CLRegion must be unique. Scheduling multiple UNNotificationRequests with different regions containing the same identifier will result in undefined behavior. The number of UNLocationNotificationTriggers that may be scheduled by an application at any one time is limited by the system. Applications must have "when-in-use" authorization through CoreLocation. See the CoreLocation documentation for more information.
__IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED
@interface UNLocationNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly, copy) CLRegion *region;
+ (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)repeats __WATCHOS_PROHIBITED;
@end
猛地一看貌似也很多的樣子踊沸,但是仔細(xì)一看就發(fā)現(xiàn)了端倪:
這里不僅僅是UNNotificationTrigger
一個類歇终,還包含了以下四個類:
// UNPushNotificationTrigger can be sent from a server using Apple Push Notification Service. UNPushNotificationTrigger
// UNTimeIntervalNotificationTrigger can be scheduled on the device to notify after the time interval, and optionally repeat. UNTimeIntervalNotificationTrigger
// UNCalendarNotificationTrigger can be scheduled on the device to notify based on date and time values, and optionally repeat. For example, if a notification should be delivered at the next 8:00 AM then set the 'hour' property of dateComponents to 8. If the notification should be delivered every day at 8:00 AM then set repeats to YES. UNCalendarNotificationTrigger
// UNLocationNotificationTrigger can be scheduled on the device to notify when the user enters or leaves a geographic region. The identifier on CLRegion must be unique. Scheduling multiple UNNotificationRequests with different regions containing the same identifier will result in undefined behavior. The number of UNLocationNotificationTriggers that may be scheduled by an application at any one time is limited by the system. Applications must have "when-in-use" authorization through CoreLocation. See the CoreLocation documentation for more information. UNLocationNotificationTrigger
值得一說的是,這四個類全部都是繼承自
UNNotificationTrigger
類逼龟,也就是說添加推送的方法參數(shù)trigger中评凝,我們無論是使用UNNotificationTrigger
亦或者是其子類都可以。
OK腺律,所有的介紹到現(xiàn)在為止奕短,我們已經(jīng)能夠?qū)懗鰜戆l(fā)送通知的代碼了,如下:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.badge = [NSNumber numberWithInt:1];
content.title = @"磨蹭";
content.body = @"不要磨蹭了你個懶蛋";
content.sound = [UNNotificationSound defaultSound];
// 間隔多久推送一次
// 當(dāng)前時間之后的沒分鐘推送一次(如果重復(fù)的話時間要大于等于60s)
// UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:YES];
// 定時推送
NSDateComponents *dateCom = [[NSDateComponents alloc] init];
// 每天下午兩點(diǎn)五十五分推送
dateCom.hour = 14;
dateCom.minute = 55;
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateCom repeats:YES];
UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"request1" content:content trigger:trigger];
[center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
}];
總結(jié)
新類UNUserNotificationCenter
實(shí)現(xiàn)推送相比較于上篇文章中介紹的UILocalNotification
類來說從內(nèi)容上來說匀钧,新類是將原先的類進(jìn)行了更加細(xì)致化的封裝并將新類放在新的框架UserNotifications
中翎碑,各個類功能分工更加明確,使用起來也更加簡便。
友情鏈接:iOS8 本地推送 UILocalNotification
如有不足之處铺董,歡迎指出嗤栓。