2012-04-29 2 views
0

У меня есть этот кусок кода, который я использую для стрельбы местного уведомления каждый день в середине ночи:UILocalNotification - Огонь и повторить в определенное время каждый день

//Get todays midnight 
    NSDate *alertTime = [NSDate date]; 
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 
    NSUInteger preservedComponents = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit); 
    alertTime = [calendar dateFromComponents:[calendar components:preservedComponents fromDate:alertTime]]; 

    UIApplication *app = [UIApplication sharedApplication]; 

    //Set up the local notification 
    UILocalNotification *notification = [[UILocalNotification alloc] init]; 
    if(notification){ 
     //Set fire date to alert time 
     notification.fireDate = alertTime; 
     //Set time zone to default 
     notification.timeZone = [NSTimeZone defaultTimeZone]; 
     //Repeat the notification everyday (fires at same time 
     //as initial notification) 
     notification.repeatInterval = NSDayCalendarUnit; 

     // schedule notification 
     [app scheduleLocalNotification:notification]; 

     NSLog(@"%@", notification.fireDate); 
    } 

Однако мне нужно другое местное уведомление стрелять каждый день в 13:00. Как это достигается? Я не понимаю, как приведенный выше код может быть адаптирован для достижения этой цели ..

Спасибо большое,

Джек

+0

посмотреть мой ответ, там namaztimes - это мой массив, у которого есть время стрельбы в нем, в этом коде мне нужно стрелять по локальной нотификации 5 раз в день (например, каждый день), так что, согласно его настройке, вы можете настроить его – Charan

ответ

3

Если у вас есть время, которое вы должны стрелять уведомления каждый день, вы должны сделать это

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [[NSDateComponents alloc] init]; 
    for (NSMutableArray * arrDay in self.namaztimes) { 
     NSLog(@"Alarm Array: %@", arrDay); 
     int count=[arrDay count]; 
     if(!count){ 
      continue; 
     } 

     int day =0; 
     int month=0; 
     int year=0; 
     int hour =0; 
     int minutes=0; 

     // NSArray *arrDates=[[NSMutableArray alloc] initWithCapacity:1]; 
     for (int i=0;i<3;i++) { 
      NSString * dayTime=[arrDay objectAtIndex:i ]; 
      if (i==0) { 
       day = [dayTime intValue];  
      }else if(i==1){ 
       month = [dayTime intValue];      
      }else if(i==2){ 
       year = [dayTime intValue];  

      } 
     } 
     for (int i=3;i<count;i++) { 
      NSString * dayTime=[arrDay objectAtIndex:i ]; 
      hour = [[dayTime substringToIndex:2] intValue]; 
      minutes = [[dayTime substringFromIndex:3] intValue]; 

      [components setDay:day]; 
      [components setMonth:month]; 
      [components setYear:year]; 
      [components setMinute:minutes]; 
      [components setHour:hour]; 


      NSDate *myNewDate = [calendar dateFromComponents:components]; 

      [self scheduleNotificationForDate:myNewDate]; 

     } 
    } 

    [components release]; 
    [calendar release]; 

то отсюда будет подключаться к основной методе уведомления огневого
[self scheduleNotificationForDate:myNewDate];

-(void) scheduleNotificationForDate: (NSDate*)date { 
    /* Here we cancel all previously scheduled notifications */ 
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; 
    UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 
    localNotification.fireDate = date; 
    NSLog(@"Notification will be shown on: %@ ",localNotification.fireDate); 

    localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
    localNotification.alertBody = @"Your Notification Text"; //[NSString stringWithFormat:@"%@",date]; 
    localNotification.alertAction = NSLocalizedString(@"View details", nil); 

    /* Here we set notification sound and badge on the app's icon "-1" 
    means that number indicator on the badge will be decreased by one 
    - so there will be no badge on the icon */ 

    localNotification.repeatInterval = NSDayCalendarUnit; 
    localNotification.soundName = UILocalNotificationDefaultSoundName; 
    localNotification.applicationIconBadgeNumber = -1; 

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
} 
+0

whats это self.namaztimes !! –

+0

Thats my array, которые имеют разные тайминги для запуска локальных уведомлений с определенными таймингами, я уже добавил комментарий к вопросу, чтобы указать его – Charan

+0

localNotification.applicationIconBadgeNumber = -1; почему -1? По моему опыту, набор уведомлений с использованием repeatInterval не показывает правильный счет на значке приложения? – Ahmed