使用ios 10 + Objective c中的本地通知在多天内设置警报

时间:2017-02-20 06:14:40

标签: objective-c ios10 uilocalnotification unusernotificationcenter

我使用UNUserNotificationCenter进行本地通知。我想在当前日期的多天内发出本地通知,如果用户选择重复,那么每周在同一天和同一时间通知用户选择哪天。所以我使用下面的代码。

 NSDate *now = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:now];//get the required calendar units

if (components.weekday>4)
{
    components.weekOfYear+=1;//if already passed monday, make it next monday
}
components.weekday = 4;//Wednesday
components.hour = 12;
NSDate *fireDate = [calendar dateFromComponents:components];
UNUserNotificationCenter *centerMonday;

UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = @"change time";
objNotificationContent.body = @"This is local notification message! Every Wednesday";
objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);


 NSDateComponents *triggerDate = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:fireDate];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:YES];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"swami12"
                                                                      content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
centerMonday = [UNUserNotificationCenter currentNotificationCenter];
centerMonday.delegate= self;
[centerMonday addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error)
 {
     if (!error)
     {
         NSLog(@"Local Notification succeeded");
     }
     else
     {

         NSLog(@"Local Notification failed");
     }
 }];

所以在这里我设置重复是,但通知在选定日期只出现一次,而不是每周重复。帮助,我从最近三天开始坚持到这里。谢谢

0 个答案:

没有答案