iOS10本地通知UserNotifications快速入門

notification.png

iOS10更新變動最大的就是通知這部分了,新版通知變得更加統一,使用更加方便,設計更加自由。以前本地通知和遠程推送是分開的,雖然這些到了iOS10都合在一起了,但是為了便于理解,我們還是把他倆分開來進行學習。這節(jié)我們學習的是本地通知。

以下的用語,如無特別表述,通知就代表本地通知,推送就代表遠程服務器的推送。

快速添加一個通知

我們先舉個完整的代碼例子,大家了解下這個流程,然后分步介紹這幾項:

//第一步:注冊通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//請求獲取通知權限(角標,聲音,彈框)
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted) {
        //獲取用戶是否同意開啟通知
        NSLog(@"request authorization successed!");
    }
}];
}
//第二步:新建通知內容對象
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]
content.title = @"iOS10通知";
content.subtitle = @"新通知學習筆記";
content.body = @"新通知變化很大,之前本地通知和遠程推送是兩個類,現在合成一個了。這是一條測試通知,";
content.badge = @1;
UNNotificationSound *sound = [UNNotificationSound soundNamed:@"caodi.m4a"];
content.sound = sound;

//第三步:通知觸發(fā)機制。(重復提醒,時間間隔要大于60s)
UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];

//第四步:創(chuàng)建UNNotificationRequest通知請求對象
NSString *requertIdentifier = @"RequestIdentifier";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requertIdentifier content:content trigger:trigger1];

//第五步:將通知加到通知中心
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    NSLog(@"Error:%@",error);

}];

最終效果如下:

notification01.png

通知內容UNMutableNotificationContent

通知內容就是設定通知的一些展示信息,iOS10之后可以設置subtitle。
聲音的設置需要借助一個新類UNNotificationSound,通知文件要放到bundle里面。另外在實際的測試過程中發(fā)現,添加通知的聲音有時候會無效。這應該是iOS10存在的一個bug,刪除掉程序,再安裝運行就好了。

觸發(fā)機制UNNotificationTrigger

Trigger是新加入的一個功能,通過此類可設置本地通知觸發(fā)條件。它一共有一下幾種類型:
1、UNPushNotificaitonTrigger
推送服務的Trigger,由系統創(chuàng)建
2、UNTimeIntervalNotificaitonTrigger
時間觸發(fā)器,可以設置多長時間以后觸發(fā),是否重復。如果設置重復,重復時長要大于60s
3、UNCalendarNotificaitonTrigger
日期觸發(fā)器,可以設置某一日期觸發(fā)。例如,提醒我每天早上七點起床:

  NSDateComponents *components = [[NSDateComponents alloc] init];
  components.hour = 7;
  components.minute = 0; // components 日期            
  UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];

4、UNLocationNotificaitonTrigger
位置觸發(fā)器,用于到某一范圍之后,觸發(fā)通知。通過CLRegion設定具體范圍。

通知請求UNNotificationRequest

通知請求的構造
+ (instancetype)requestWithIdentifier:(NSString *)identifier content:(UNNotificationContent *)content trigger:(nullable UNNotificationTrigger *)trigger;
就是把上面三項連接起來。它有一個參數identifier,這相當于通知的一個身份。iOS10通知支持更新,就是基于此identifier再發(fā)一條通知。

通知中心UNUserNotificationCenter

獲取通知[UNUserNotificationCenter currentNotificationCenter]然后通過addNotificaitonRequest:就完成了一個通知的添加。

擴展通知的內容

通知我們已經添加上了,現在我們需要擴展一下通知的內容,給它加一些內容。擴展的內容需要支持3D-touch的手機(6s以上),重壓之后全面顯示

添加附件

iOS10之前通知的樣式不能更改,在iOS10之后引入了UNNotificationationAttachment,可以在通知中添加圖片,音頻,視頻。蘋果對這些附件的大小和類型有一個限制:


attachment_type.png

如果我想在通知里加一個圖片,可以這樣處理:

NSString *imageFile = [[NSBundle mainBundle] pathForResource:@"sport" ofType:@"png"];
UNNotificationAttachment *imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"iamgeAttachment" URL:[NSURL fileURLWithPath:imageFile] options:nil error:nil];
content.attachments = @[imageAttachment];//雖然是數組,但是添加多個只能顯示第一個
/* add request and notificaiton code ... */

效果如下:

notification02.png

重壓之后:


notificaiton03.png

添加交互

//點擊可以顯示文本輸入框
UNTextInputNotificationAction *action1 = [UNTextInputNotificationAction actionWithIdentifier:@"replyAction" title:@"文字回復" options:UNNotificationActionOptionNone];
//點擊進入應用
UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"enterAction" title:@"進入應用" options:UNNotificationActionOptionForeground];
//點擊取消,沒有任何操作
UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"cancelAction" title:@"取消" options:UNNotificationActionOptionDestructive];
//通過UNNotificationCategory對象將這幾個action行為添加到通知里去
UNNotificationCategory *categroy = [UNNotificationCategory categoryWithIdentifier:@"Categroy" actions:@[action1,action2,action3] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
//將categroy賦值到通知內容上
content.categoryIdentifier = @"Categroy";
//設置通知代理,用于檢測點擊方法
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
/* add request and notificaiton code ... */

效果如下:

notificaiotn04.png
notification05.png

獲取通知交互內容:

//識別通知交互處理的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{

NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;

if ([categoryIdentifier isEqualToString:@"Categroy"]) {
    //識別需要被處理的拓展
    if ([response.actionIdentifier isEqualToString:@"replyAction"]){
        //識別用戶點擊的是哪個 action
        UNTextInputNotificationResponse *textResponse = (UNTextInputNotificationResponse*)response;
        //獲取輸入內容
        NSString *userText = textResponse.userText;
        //發(fā)送 userText 給需要接收的方法
        NSLog(@"要發(fā)送的內容是:%@",userText);
        //[ClassName handleUserText: userText];
    }else if([response.actionIdentifier isEqualToString:@"enterAction"]){
        NSLog(@"點擊了進入應用按鈕");
    }else{
        NSLog(@"點擊了取消");
    }
}
completionHandler();
}

由此我們可以知道action,categroy,request這些東西都是通過各自的identifier獲取的。這樣可以很方便的定位到某一個通知或者action上,為交互的處理提供了很大的便利。

自定義通知樣式

在Xcode中File->New->Targe會出現下面的視圖

notification06.png

Notification Content對應的是通知,Notification Service Extension對應的是推送。我們這里要實現通知的自定義,選擇左邊那個。創(chuàng)建成功之后會在工程里多一個文件件
notification07.png

NotificationViewController文件是自動生成的,里面有一個
- (void)didReceiveNotification:(UNNotification *)notification
可以在這里定義一些通知的顯示。

MainInterface.storyboard文件是控制通知的storyboard文件,可以編輯需要的通知樣式。我們設計一下文字的顏色和顯示位置

notificaiton08.png

接下來你可能會問,怎么把這個自定義的通知樣式應用到當前通知里呢?先別急,我們看下一個文件Info.flist里面的內容

notification09.png

第一項UNNotificationExtensionCategory就是UNNotificationCategory的標示,我們把他換成我們通知里使用的標示"Category",系統就會自動匹配通知顯示的樣式。
第二項UNNotificationExtensionIntialContentSizeRation初始內容 Size 的比例。也可以在 viewDidLoad 中使用 self.preferredContentSize 直接設置 Size。
第三項UNNotificationExtensionDefaultContentHidden是否隱藏默認內容,如果設為YES,默認內容會被隱藏。
顯示的效果:

notification10.png

總結

至此,iOS通知部分的內容就學完了,參考代碼:Demo
參考文檔:
iOS10 User Notificaitons學習筆記
活久見的重構-iOS10 UserNotificaiotns框架解析

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容