iOS开发本地推送

最近有个小需求,做一个本地的事件通知,要求选择起始时间和推送的时间间隔,并且要每天推送。借着这个机会把本地推送方面的知识有梳理一遍。

先来看一下大致的功能需求如下图:


1.png
主要实现原理
1. AppDelegate中设置

推送的样式,提醒用户使用推送原因(系统权限提醒)

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
UNAuthorizationOptions types=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
 [center requestAuthorizationWithOptions:types completionHandler:^(BOOL granted, NSError * _Nullable error) {

  }];

根据granted的状态也能判断开关是否打开,如果是只有推送功能的APP,只有打开推送才能使用的话,这里就可以写跳转设置的代码。(APP首次运行,系统弹出时候允许推送,不允许直接跳转设置)

2.创建推送前的判断

判断通知开关是否打开,没有打开弹窗提醒,是否需要跳转设置中,打开开关。(首次运行时,用户不允许推送的情况)

 [[UNUserNotificationCenter currentNotificationCenter]getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
          if ( settings.authorizationStatus==UNAuthorizationStatusAuthorized) {
               NSLog(@"通知开关打开");
          }else{
                  dispatch_async(dispatch_get_main_queue(), ^{

                    UIAlertController *shetVC = [UIAlertController alertControllerWithTitle:@"Tip" message:@"Open notifications in settings" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"Cancle" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    UIAlertAction *done = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@""} completionHandler:^(BOOL success) { }];
                    }];
                    [shetVC addAction:cancle];
                    [shetVC addAction:done];
                    [self presentViewController:shetVC animated:YES completion:nil];
              });
        }
  }];
3.创建推送
  • 用起始日期的方式实现每天的循环
-(void)addLocationNotifitionWithFrency:(NSString*)startTime endTime:(NSString*)endTime{
    
    NSArray *startArr = [startTime componentsSeparatedByString:@":"];
    NSInteger hour_start   = [startArr[0]integerValue];
    NSInteger minute_start = [startArr[1]integerValue];
    NSInteger num = 0;
    //时间间隔
    if ([self.timeBaseView.interValLable.text isEqualToString:@"1 hours"]) {
        num = 1;
    }else if ([self.timeBaseView.interValLable.text isEqualToString:@"2 hours"]){
        num = 2;
    }else if([self.timeBaseView.interValLable.text isEqualToString:@"3 hours"]){
        num = 3;
    }else if ([self.timeBaseView.interValLable.text isEqualToString:@"4 hours"]){
        num = 4;
    }else{
        num = 5;
    }
    //
    NSInteger cha_hour = [NSString chaEndTimeAndStartTime:startTime endTime:endTime];
    NSInteger cha      = cha_hour/num;//计算出起始时间内有多少个num(间隔num小时,要推送几次),
    //循环创建的时候最后一个时间(一定要区分ID,否则只会是一个推送)
    for (NSInteger index=0; index<cha; index++) {

        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = @"Wash Hand";
        content.subtitle = @"It's time to wash hand";
        content.sound = [UNNotificationSound defaultSound];
        //设置最初时间,从哪一天开始,这里可以尽可能的往前设置,只要在你最初时间之前都可以
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *dateString = [NSString stringWithFormat:@"2019-01-01 %ld:%ld:00",hour_start+index*num,minute_start];;
        NSDate * date = [formatter dateFromString:dateString];
        /*这是一个时间容器
          NSCalendarUnitYear
          NSCalendarUnitMonth
          NSCalendarUnitDay
          NSCalendarUnitHour
          NSCalendarUnitMinute
          NSCalendarUnitSecond
          NSCalendarUnitWeekday)*/
        //设置不同的容器可以实现不同的需求,这里我们是要每天推送的某时分秒推送
        NSDateComponents * components = [[NSCalendar currentCalendar]
        components:NSCalendarUnitHour |
                   NSCalendarUnitMinute |
                   NSCalendarUnitSecond
        fromDate:date];
        //两种trigger,这里UNCalendarNotificationTrigger符合我们要求
        UNCalendarNotificationTrigger * trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components
        repeats:YES];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[NSString stringWithFormat:@"time%ld",index] content:content trigger:trigger];
        //把通知加到UNUserNotificationCenter, 到指定触发点会被触发
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"通知添加失败:%@",error);
            } else {
                NSLog(@"通知添加成功");
            }
        }];
    }
}

每天都推送,那么也就是从周日到周六的七天,因此也可利用NSCalendarUnitWeekday实现,周日为本周的第一天,NSCalendarUnitWeekday中weekday这里周日到周六是用1-7

传送门:参考链接

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,367评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,959评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,750评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,226评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,252评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,975评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,592评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,497评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,027评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,147评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,274评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,953评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,623评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,143评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,260评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,607评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,271评论 2 358