专题~热更新

UNUserNotificationCenter本地推送

2019-03-27  本文已影响120人  倪大头

iOS10不推荐使用UILocalNotification进行本地推送了,UNUserNotificationCenter作为替代

AppDelegate里完成注册、代理、授权,监听方法也在里面

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //注册通知设置代理
    UNUserNotificationCenter *notiCenter = [UNUserNotificationCenter currentNotificationCenter];
    notiCenter.delegate = self;
    //用户授权
    [notiCenter requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        
    }];
    //获取当前通知设置
    [notiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        
    }];
    
    return YES;
}

//收到本地推送时调用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"推送内容 %@", notification.request.content.body);
    
    completionHandler(UNNotificationPresentationOptionSound + UNNotificationPresentationOptionAlert);
}

//点击推送弹窗时调用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    NSLog(@"点击推送 %@", response.notification.request.content.body);
}

发推送:

- (void)postNotiAction {
    UNUserNotificationCenter *notiCenter = [UNUserNotificationCenter currentNotificationCenter];
    //通知内容 UNNotificationContent或UNMutableNotificationContent
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init];
    content.badge = @1;
    content.title = @"我是标题";
    content.body = @"我是内容";
    content.sound = [UNNotificationSound defaultSound];
    //定时器推送,定时器推送若repeats为YES,必须间隔60s以上
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    
    //指定时间推送
    //NSDateComponents *dateCom = [[NSDateComponents alloc] init];
    //上午10点22推送,repeats为YES则每天推送
    //dateCom.hour = 14;
    //dateCom.minute = 22;
    //UNCalendarNotificationTrigger *dateTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateCom repeats:YES];
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"testNOti" content:content trigger:trigger];
    [notiCenter addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
    }];
}
WechatIMG1.png
上一篇 下一篇

猜你喜欢

热点阅读