屏幕快照 2017-08-22 下午6.27.45.png
我們需要新建兩個target如上圖所示,也就是我們今天要講到的NotificationService、NotificationViewController
Snip20170822_9.png
如上圖所示為新建方式
Snip20170824_11.png
新建完成以后就是如上圖所示
二、下面我們來看看上面兩個文件里面的應該怎樣使用
1:NotificationService的使用
#import "NotificationService.h"
#import "GeTuiExtSdk.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...
NSDictionary *apsDic = [[self dictionaryWithJsonString:self.bestAttemptContent.userInfo[@"payload"] ] objectForKey:@"aps"];
self.bestAttemptContent.title = @"經濟日報";
self.bestAttemptContent.subtitle = [apsDic objectForKey:@"pushtopic"];
self.bestAttemptContent.body = [NSString stringWithFormat:@"%@",[[[self.bestAttemptContent.userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"]];
// 附件
NSString *imageUrl = [NSString stringWithFormat:@"%@",[apsDic objectForKey:@"pushimageurl"]];
NSLog(@"userInfo-----%@",self.bestAttemptContent.userInfo);
NSLog(@"alert-----%@",[[self.bestAttemptContent.userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
NSLog(@"apsDic-----%@",apsDic);
// 這里添加一些點擊事件,可以在收到通知的時候,添加,也可以在攔截通知的這個擴展中添加
self.bestAttemptContent.categoryIdentifier = @"category2";
if (!imageUrl.length){
self.contentHandler(self.bestAttemptContent);
}
// 圖片下載
[self loadAttachmentForUrlString:imageUrl withType:@"jpg" completionHandle:^(UNNotificationAttachment *attach) {
if (attach)
{
self.bestAttemptContent.attachments = [NSArray arrayWithObject:attach];
}
self.contentHandler(self.bestAttemptContent);
// 個推的統計APNs到達情況
[GeTuiExtSdk handelNotificationServiceRequest:request withComplete:^
{
self.contentHandler(self.bestAttemptContent); //展示推送的回調處理需要放到個推回執完成的回調中
}];
}];
}
- (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);
}
// 下載數據
- (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){
}
else{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]];
[fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error];
NSError *attachmentError = nil;
attachment = [UNNotificationAttachment attachmentWithIdentifier:@"" URL:localURL options:nil error:&attachmentError];
if (attachmentError)
{
}
}
completionHandler(attachment);
}] resume];
}
// 判斷多媒體數據類型
- (NSString *)fileExtensionForMediaType:(NSString *)type {
NSString *ext = type;
if ([type isEqualToString:@"image"])
{
ext = @"jpg";
}
if ([type isEqualToString:@"video"])
{
ext = @"mp4";
}
if ([type isEqualToString:@"audio"])
{
ext = @"mp3";
}
return [@"." stringByAppendingString:ext];
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
return nil;
}
return dic;
}
1:NotificationViewController的使用
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
#import <AVFoundation/AVFoundation.h>
@interface NotificationViewController () <UNNotificationContentExtension>
@property IBOutlet UILabel *label;
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, copy) void (^completion)(UNNotificationContentExtensionResponseOption option);
@end
@implementation NotificationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any required interface initialization here.
}
// 按鈕的點擊事件
- (void)didReceiveNotification:(UNNotification *)notification {
self.label.text = notification.request.content.body;
}
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion
{
if ([response.actionIdentifier isEqualToString:@"action-open"]){ // 打開
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:@"action-cancel"]){ // 取消、不打開
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
completion(UNNotificationContentExtensionResponseOptionDismissAndForwardAction);
});
}
else if ([response.actionIdentifier isEqualToString:@"action-like"]) {
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"like" ofType:@"m4a"]] error:nil];
[self.player play];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.player stop];
self.player = nil;
completion(UNNotificationContentExtensionResponseOptionDismiss);
});
}
else if ([response.actionIdentifier isEqualToString:@"action-collect"]){
self.label.text = @"收藏成功~";
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:@"action-comment"]){
self.label.text = [(UNTextInputNotificationResponse *)response userText];
}
//這里如果點擊的action類型為UNNotificationActionOptionForeground,
//則即使completion設置成Dismiss的,通知也不能消失
}
@end
我們需要注冊遠程通知
/*
警告:該方法需要開發者自定義,以下代碼根據APP支持的iOS系統不同,代碼可以對應修改。
以下為演示代碼,注意根據實際需要修改,注意測試支持的iOS系統都能獲取到DeviceToken
*/
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8編譯會調用
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
// 設置
[self addCustomUICategory];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7編譯會調用
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}
- (void)addCustomUICategory
{
// --- openAction
UNNotificationAction *openAction = [UNNotificationAction actionWithIdentifier:@"action-open" title:@"查看" options:UNNotificationActionOptionForeground];
//
UNNotificationAction *cancelAction = [UNNotificationAction actionWithIdentifier:@"action-cancel" title:@"不感興趣" options:UNNotificationActionOptionAuthenticationRequired];
// --- likeAction
// UNNotificationAction *likeAction = [UNNotificationAction actionWithIdentifier:@"action-like" title:@"贊" options:UNNotificationActionOptionAuthenticationRequired];
// // --- collectAction
// UNNotificationAction *collectAction = [UNNotificationAction actionWithIdentifier:@"action-collect" title:@"收藏" options:UNNotificationActionOptionDestructive];
// // --- commentAction
// UNTextInputNotificationAction *commentAction = [UNTextInputNotificationAction actionWithIdentifier:@"action-comment" title:@"評論" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"發送" textInputPlaceholder:@"輸入你的評論"];
// --- 組裝
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"category2" actions:@[openAction, cancelAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
}