iOS 通知擴展

級別: ★★☆☆☆
標籤:「iOS通知擴展」「iOS推送擴展」「UNNotificationServiceExtension」「UNNotificationContentExtension」
做者: dac_1033
審校: QiShare團隊php


iOS10以後的通知具備擴展功能,能夠在系統收到通知、展現通知時作一些事情。下面是實現步驟要點介紹:git

1. 建立UNNotificationServiceExtension和UNNotificationContentExtension:

  • UNNotificationServiceExtension:通知服務擴展,是在收到通知後,展現通知前,作一些事情的。好比,增長附件,網絡請求等。點擊查看官網文檔
  • UNNotificationContentExtension:通知內容擴展,是在展現通知時展現一個自定義的用戶界面。點擊查看官網文檔

建立兩個target
建立兩個target的結果
注意:

  • 如上圖默認狀況下,兩個新生成target的bundleId是主工程名字的bundleId.target名稱,不須要修改;
  • target支持的iOS版本爲10.0及以上。

2. 通知服務擴展UNNotificationServiceExtension

在NotificationService.m文件中,有兩個方法:github

// 系統接到通知後,有最多30秒在這裏重寫通知內容(以下載附件並更新通知)
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler;
// 處理過程超時,則收到的通知直接展現出來
- (void)serviceExtensionTimeWillExpire;
複製代碼

代碼示例以下:數組

#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    //// Modify the notification content here...
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    
    // 注:爲通知下拉手動展開時,可添加多個事件
    // UNNotificationActionOptions包含三個值UNNotificationActionOptionAuthenticationRequired、UNNotificationActionOptionDestructive、UNNotificationActionOptionForeground
    UNNotificationAction * actionA  =[UNNotificationAction actionWithIdentifier:@"ActionA" title:@"Required" options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"ActionB" title:@"Destructive" options:UNNotificationActionOptionDestructive];
    UNNotificationAction * actionC = [UNNotificationAction actionWithIdentifier:@"ActionC" title:@"Foreground" options:UNNotificationActionOptionForeground];
    UNTextInputNotificationAction * actionD = [UNTextInputNotificationAction actionWithIdentifier:@"ActionD"
                                                                                            title:@"Input-Destructive"
                                                                                          options:UNNotificationActionOptionDestructive
                                                                             textInputButtonTitle:@"Send"
                                                                             textInputPlaceholder:@"input some words here ..."];
    NSMutableArray *actionArr = [[NSMutableArray alloc] initWithObjects:actionA, actionB, actionC, actionD, nil];
    if (actionArr.count) {
        UNNotificationCategory * notficationCategory = [UNNotificationCategory categoryWithIdentifier:@"categoryNoOperationAction"
                                                                                              actions:actionArr
                                                                                    intentIdentifiers:@[@"ActionA",@"ActionB",@"ActionC",@"ActionD"]
                                                                                              options:UNNotificationCategoryOptionCustomDismissAction];
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:notficationCategory]];
    }
    
    
    // 注:1.通知擴展功能須在aps串中設置字段"mutable-content":1; 2.多媒體的字段能夠與appServer協議制定;
    self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
    
    NSDictionary *userInfo =  self.bestAttemptContent.userInfo;
    NSString *mediaUrl = [NSString stringWithFormat:@"%@", userInfo[@"media"][@"url"]];
    if (!mediaUrl.length) {
        self.contentHandler(self.bestAttemptContent);
    } 
    else {
        [self loadAttachmentForUrlString:mediaUrl withType:userInfo[@"media"][@"type"] completionHandle:^(UNNotificationAttachment *attach) {
            if (attach) {
                self.bestAttemptContent.attachments = [NSArray arrayWithObject:attach];
            }
            self.contentHandler(self.bestAttemptContent);
        }];
    }
}

- (void)loadAttachmentForUrlString:(NSString *)urlStr withType:(NSString *)type completionHandle:(void(^)(UNNotificationAttachment *attach))completionHandler {
    __block UNNotificationAttachment *attachment = nil;
    NSURL *attachmentURL = [NSURL URLWithString:urlStr];
    NSString *fileExt = [self fileExtensionForMediaType:type];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session downloadTaskWithURL:attachmentURL completionHandler:^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) {
        if (error != nil) {
            NSLog(@"加載多媒體失敗 %@", error.localizedDescription);
        } 
        else {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]];
            [fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error];
            // 自定義推送UI須要
            NSMutableDictionary * dict = [self.bestAttemptContent.userInfo mutableCopy];
            [dict setObject:[NSData dataWithContentsOfURL:localURL] forKey:@"image"];
            self.bestAttemptContent.userInfo = dict;
            
            NSError *attachmentError = nil;
            attachment = [UNNotificationAttachment attachmentWithIdentifier:@"" URL:localURL options:nil error:&attachmentError];
            if (attachmentError) {
                NSLog(@"%@", attachmentError.localizedDescription);
            }
        }
        completionHandler(attachment);
    }] resume];
}

- (NSString *)fileExtensionForMediaType:(NSString *)type {
    NSString *ext = type;
    if ([type isEqualToString:@"image"]) {
        ext = @"jpg";
    }
    else if ([type isEqualToString:@"video"]) {
        ext = @"mp4";
    }
    else if ([type isEqualToString:@"audio"]) {
        ext = @"mp3";
    }
    return [@"." stringByAppendingString:ext];
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end
複製代碼

aps串格式: {"aps":{"alert":{"title":"Title...","subtitle":"Subtitle...","body":"Body..."},"sound":"default","badge": 1,"mutable-content": 1,"category": "realtime",},"msgid":"123","media":{"type":"image","url":"www.fotor.com/images2/fea…"}}bash

說明:微信

  • 加載並處理附件的時間要在30秒以內,纔會達到預期效果;
  • UNNotificationAttachment的url參數接收的是本地文件的url;
  • 服務端在處理推送內容時,須要加上文件類型字段;
  • aps字符串中的mutable-content字段須要設置爲1;
  • 在對NotificationService這個target打斷點debug的時候,須要在XCode頂欄選擇編譯運行的target爲NotificationService,不然沒法進行實時debug。

3. 通知內容擴展UNNotificationContentExtension

通知內容擴展過程當中,展現在用戶面前的NotificationViewController的結構說明如圖以下: 網絡

通知內容擴展界面

一、設置actions: 從NotificationViewController這個類能夠看出,它直接繼承於ViewController,所以能夠在這個類中重寫相關方法,來修改界面的相關佈局及樣式。在這個界面展開以前,用戶經過UNNotificationAction仍是能夠與相應推送通知交互的,可是***用戶和這個通知內容擴展界面沒法直接交互***。(這些actions有兩種設置途徑:用戶能夠經過在AppDelegate中實例化UIUserNotificationSettings來間接設置這些actions;在UNNotificationServiceExtension中也能夠處理這些actions。)session

二、設置category: 推送通知內容中的category字段,與UNNotificationContentExtension的info.plist中UNNotificationExtensionCategory字段的值要匹配到,系統才能找到自定義的UI。app

在aps字符串中直接設置category字段以下:ide

{ "aps":{ "alert":"Testing...(0)","badge":1,"sound":"default","category":"QiShareCategoryIdentifier"}}
複製代碼

在NotificationService.m中設置category的值以下:

self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
複製代碼

info.plist中關於category的配置以下:

關於UNNotificationExtensionCategory的設置

三、UNNotificationContentExtension協議:NotificationViewController 中生成時默認實現了。

簡單的英文註釋很明瞭:

// This will be called to send the notification to be displayed by
// the extension. If the extension is being displayed and more related
// notifications arrive (eg. more messages for the same conversation)
// the same method will be called for each new notification.
- (void)didReceiveNotification:(UNNotification *)notification;

// If implemented, the method will be called when the user taps on one
// of the notification actions. The completion handler can be called
// after handling the action to dismiss the notification and forward the
// action to the app if necessary.
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion

// Called when the user taps the play or pause button.
- (void)mediaPlay;
- (void)mediaPause;
複製代碼

四、UNNotificationAttachment:attachment支持

  • 音頻5M(kUTTypeWaveformAudio/kUTTypeMP3/kUTTypeMPEG4Audio/kUTTypeAudioInterchangeFileFormat)
  • 圖片10M(kUTTypeJPEG/kUTTypeGIF/kUTTypePNG)
  • 視頻50M(kUTTypeMPEG/kUTTypeMPEG2Video/kUTTypeMPEG4/kUTTypeAVIMovie)

自定義內容擴展界面示例代碼以下:

#import "NotificationViewController.h"
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>

#define Margin 15

@interface NotificationViewController () <UNNotificationContentExtension>

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UILabel *subLabel;
@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) UILabel *hintLabel;

@end

@implementation NotificationViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    
    CGPoint origin = self.view.frame.origin;
    CGSize size = self.view.frame.size;
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(Margin, Margin, size.width-Margin*2, 30)];
    self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.label];
    
    self.subLabel = [[UILabel alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.label.frame)+10, size.width-Margin*2, 30)];
    self.subLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.subLabel];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.subLabel.frame)+10, 100, 100)];
    [self.view addSubview:self.imageView];
    
    self.hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.imageView.frame)+10, size.width-Margin*2, 20)];
    [self.hintLabel setText:@"我是hintLabel"];
    [self.hintLabel setFont:[UIFont systemFontOfSize:14]];
    [self.hintLabel setTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:self.hintLabel];
    self.view.frame = CGRectMake(origin.x, origin.y, size.width, CGRectGetMaxY(self.imageView.frame)+Margin);

    // 設置控件邊框顏色
    [self.label.layer setBorderColor:[UIColor redColor].CGColor];
    [self.label.layer setBorderWidth:1.0];
    [self.subLabel.layer setBorderColor:[UIColor greenColor].CGColor];
    [self.subLabel.layer setBorderWidth:1.0];
    [self.imageView.layer setBorderWidth:2.0];
    [self.imageView.layer setBorderColor:[UIColor blueColor].CGColor];
    [self.view.layer setBorderWidth:2.0];
    [self.view.layer setBorderColor:[UIColor cyanColor].CGColor];
}

- (void)didReceiveNotification:(UNNotification *)notification {
    
    self.label.text = notification.request.content.title;
    self.subLabel.text = [NSString stringWithFormat:@"%@ [ContentExtension modified]", notification.request.content.subtitle];
    
    NSData *data = notification.request.content.userInfo[@"image"];
    UIImage *image = [UIImage imageWithData:data];
    [self.imageView setImage:image];
}

- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion {
    
    [self.hintLabel setText:[NSString stringWithFormat:@"觸發了%@", response.actionIdentifier]];
    if ([response.actionIdentifier isEqualToString:@"ActionA"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            completion(UNNotificationContentExtensionResponseOptionDismiss);
        });
    } else if ([response.actionIdentifier isEqualToString:@"ActionB"]) {

    } else if ([response.actionIdentifier isEqualToString:@"ActionC"]) {

    }  else if ([response.actionIdentifier isEqualToString:@"ActionD"]) {

    } else {
        completion(UNNotificationContentExtensionResponseOptionDismiss);
    }
    completion(UNNotificationContentExtensionResponseOptionDoNotDismiss);
}

@end
複製代碼

說明:

  • 宿主工程、服務擴展target和內容擴展target三者中支持的系統版本號要一致。
  • 自定義視圖的大小能夠經過設置NotificationViewController的preferredContentSize大小來控制,可是用戶體驗稍顯突兀,能夠經過設置info.plist中的UNNotificationExtensionInitialContentSizeRatio屬性的值來優化;
  • contentExtension中的info.plist中NSExtension下的NSExtensionAttributes字段下能夠配置如下屬性的值,UNNotificationExtensionCategory:表示自定義內容假面能夠識別的category,能夠爲數組,便可覺得這個content綁定多個通知;UNNotificationExtensionInitialContentSizeRatio:默認的UI界面的高寬比;UNNotificationExtensionDefaultContentHidden:是否顯示系統默認的標題欄和內容,可選參數;UNNotificationExtensionOverridesDefaultTitle:是否讓系統採用消息的標題做爲通知的標題,可選參數。
  • 處理通知內容擴展的過程當中關於identifier的設置共有五處(UNNotificationAction、UNNotificationCategory、bestAttemptContent、contentExtension中的info.plist中,aps字符串中),請區別不一樣identifier的做用。
  • 兩個擴展聯合使用,在XCode中選擇當前target,才能打斷點看到相應log信息。

工程源碼:GitHub地址

關注咱們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公衆號)

推薦文章:
iOS 本地通知
iOS 遠程通知

相關文章
相關標籤/搜索