IOS本地通知

来源:互联网 发布:淘宝装修工具2.1 编辑:程序博客网 时间:2024/06/05 16:51

由于IOS10以后更新了通知的类。所以我们必须要学会判断当前设备的版本,ios10以前的设备仍然使用以前的写法。ios10以后使用新写法。如果还不会判断版本的。请参考上一篇微博:
http://blog.csdn.net/lee727n/article/details/72757831
发送本地通知代码及注释如下:

- (void)viewDidLoad {    [super viewDidLoad];//    ios10以前的写法://    UILocalNotification *noti = [[UILocalNotification alloc]init];//    noti.userInfo = @{@"name":@"hehe"};//    //    noti.repeatInterval = NSCalendarUnitMinute;//    //    noti.alertBody = @"lalala body";//    //    noti.applicationIconBadgeNumber = 5;//    //开始时间//    noti.fireDate = [[NSDate new] dateByAddingTimeInterval:5];//    //    [[UIApplication sharedApplication] scheduleLocalNotification:noti];    //iOS 10以后的写法    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];     [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {        if (!error) {            NSLog(@"request authorization succeeded!");            center.delegate = self;        }    }];    //Local Notification    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];    content.title = @"我是标题";    content.subtitle = @"呵呵哈哈";    content.body = @"啦啦啦啦啦啦啦";    content.badge = @1;    //设置传递的参数    content.userInfo = @{@"name":@"小明",@"age":@18};    //2 分钟后提醒    //如果repeats 重复 必须60秒以上    UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:120 repeats:NO];    //每小时重复 1 次喊我喝水//    UNTimeIntervalNotificationTrigger *trigger2 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:2600 repeats:YES];////    //每周一早上 8:00 提醒我给老婆做早饭//    NSDateComponents *components = [[NSDateComponents alloc] init];//    components.weekday = 2;//    components.hour = 8;//    UNCalendarNotificationTrigger *trigger3 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];    NSString *requestIdentifier = @"sampleRequest";    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier                                                                          content:content                                                                          trigger:trigger1];    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {        NSLog(@"添加完成:%@",error);    }];}

将要发出通知的时候,还有一个代理方法可以使用

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{    NSDictionary *userInfo = notification.request.content.userInfo;    NSString *name = userInfo[@"name"];    NSNumber *age = userInfo[@"age"];    NSLog(@"%@  %@",name,age);}

实现效果如下:
这里写图片描述

原创粉丝点击