iOS - 推送


本地推送

一.创建UNUserNotificationCenter,设置推送模式和代理

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
//注册通知 
/*提醒方式
	UNAuthorizationOptionSound
  UNAuthorizationOptionAlert
  UNAuthorizationOptionBadge
*/
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {

    if (granted) {
        NSLog(@"同意开启通知");
    }

}];

二.实现代理

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"将要推送");
    //设置APP在前台时也展示通知
    completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSLog(@"已经完成推送");
}

三.创建通知

以下是我用到的场景,在一个起止日期里进行推送

/// 添加本地推送
/// @param title 通知的标题
/// @param subTitle 通知的副标题
/// @param body 通知的内容
/// @param identifier 通知的标识
/// @param startDate 通知的开始日期(包含)
/// @param endDate 通知的结束日期(包含)
/// @param hour 通知的小时
/// @param minute 通知的分钟
/// @param second 通知的秒钟
- (void)addLocalNotificationWithTitle:(NSString *)title subTitle:(NSString *)subTitle body:(NSString *)body identifier:(NSInteger)identifier startDate:(NSString *)startDate endDate:(NSString *)endDate hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second {
    
    //标题或者内容都没有的情况下不通知
    if (title.length == 0 && body.length == 0) {
        return;
    }
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    
    //标题
    if (title.length) {
        content.title = title;
    }
    //副标题
    if (subTitle.length) {
        content.subtitle = subTitle;
    }
    //内容
    if (body.length) {
        content.body = body;
    }
    
    
    //声音 - 默认
    content.sound = [UNNotificationSound defaultSound];
    
    //角标
//    content.badge = @1;
    
    
    //获取起止时间段的日期数组
    NSArray *dateArr = [self getDateArrWithStartDate:startDate endDate:endDate];
  	NSLog(@"需要推送的日期数组 - %@",dateArr);
    
    //遍历数组,逐个添加通知
    for (NSInteger i = 0; i < dateArr.count; i++) {
        //获取推送日期
        NSString *dateStr = dateArr[i];
      	NSLog(@"当前要推送的日期 - %@",dateStr);
        
        //将日期转为对应的年、月、日
        NSDateFormatter *matter = [[NSDateFormatter alloc] init];
        matter.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [matter dateFromString:dateStr];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
        
        NSInteger year = [components year];
        NSInteger month = [components month];
        NSInteger day = [components day];

//        NSLog(@"year: %ld  month: %ld  day: %ld",(long)year,(long)month,(long)day);
        
        //定时推送
        NSDateComponents *dateCom = [[NSDateComponents alloc] init];
        //年
        dateCom.year = year;
        //月
        dateCom.month = month;
        //日
        dateCom.day = day;
        //时
        dateCom.hour = hour;
        //分
        dateCom.minute = minute;
        
        //标识identifier
        identifier = identifier * (i+1);

        //推送方式
        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateCom repeats:NO];
        
        //給通知添加标识
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[NSString stringWithFormat:@"%ld",(long)identifier] content:content trigger:trigger];
        
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            
            if (error) {
                NSLog(@"本地推送添加失败 - %@",error);
            } else {
                NSLog(@"本地推送添加成功");
            }
            
        }];
        
    }
    
}

获取两个日期之间所有日期数组,精确到天

/// 获取两个日期之间所有日期数组,精确到天
/// @param startDateStr 开始日期
/// @param endDateStr 结束日期
- (NSArray *)getDateArrWithStartDate:(NSString *)startDateStr endDate:(NSString *)endDateStr {
    
    // 计算两个时间的差值
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据 NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSCalendarUnit unit = NSCalendarUnitDay;
    
    NSDateFormatter *dateMatter = [[NSDateFormatter alloc] init];
    dateMatter.dateFormat = @"yyyy-MM-dd";
    NSDate *beginDate = [dateMatter dateFromString:startDateStr];
    NSDate *endDate = [dateMatter dateFromString:endDateStr];
    
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:beginDate toDate:endDate options:0];
     
    // 两个日期之间所有天数组成的数组
    NSMutableArray *allDayArr = [NSMutableArray new];
    for (int i = 0 ; i < dateCom.day+1 ; i ++) {
        // n天后的天数
        int days = i;
        // 一天一共有多少秒
        NSTimeInterval oneDay = 24 * 60 * 60;
        // 指定的日期
        NSDate *appointDate = [NSDate dateWithTimeInterval:oneDay * days sinceDate:beginDate];
        // 转字符串
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"]; // @"yyyy-MM-dd"
        NSString *appointTime = [dateFormatter stringFromDate:appointDate];
        [allDayArr addObject:appointTime];

    }
        return allDayArr;
}

四.移除通知

//移除所有通知
[[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];

//根据ID移除通知
[[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[requestID]];

文章作者: 逸之
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 逸之 !
  目录