1

我使用 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");
     }
 }];

所以在这里我设置了重复是但通知只在选定的一天出现一次,而不是每周重复一次。帮助,我从过去三天就卡在这里了。谢谢

4

0 回答 0