Question

Je fais une application iPhone, qui a besoin des notifications locales.

Dans les notifications locales il y a repeatInterval propriété où l'on peut mettre les intervalles de répétition de l'unité pour mintute, heure, jour, semaine, année, etc.

Je veux que l'intervalle de répétition doit être de 4 heures.

Alors toutes les 4 heures la notification locale vient.

Je ne veux pas que l'utilisateur de définir des notifications séparées pour chacun.

Je veux que l'utilisateur soit en mesure de mettre repeatInterval en 4 heures.

Comment puis-je faire?

Était-ce utile?

La solution

obtenu la réponse, il est aussi droit qu'il obtient.

Vous ne pouvez pas créer des intervalles réguliers sur mesure.

Vous devez utiliser sur l'unité de NSCalendarUnit en construction Intervalles .

J'ai essayé toutes les solutions ci-dessus et même essayé d'autres étoffes, mais aucun d'entre eux travaillaient.

J'ai investi suffisamment de temps à trouver qu'il n'y a aucun moyen que nous pouvons obtenir de travailler pour des intervalles de temps personnalisés.

Autres conseils

L'intervalle de répétition est juste un ENUM qui a une constante bit-map, donc il n'y a pas moyen d'avoir repeatIntervals personnalisé, juste chaque minute, chaque seconde, chaque semaine, etc.

Cela étant dit, il n'y a aucune raison pour votre utilisateur doit avoir à mettre chacun. Si vous laissez les deux valeurs suivantes dans votre interface utilisateur, quelque chose comme « Frequency unit: Yearly/Monthly/Weekly/Hourly » et « Every ____ years/months/weeks/hours » alors vous pouvez générer automatiquement les notifications appropriées en fixant la date d'incendie approprié sans répétition.

UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSInterval interval;
switch( freqFlag ) {     // Where freqFlag is NSHourCalendarUnit for example
    case NSHourCalendarUnit:
        interval = 60 * 60;  // One hour in seconds
        break;
    case NSDayCalendarUnit:
        interval = 24 * 60 * 60; // One day in seconds
        break;
}
if( every == 1 ) {
    locNot.fireDate = [NSDate dateWithTimeInterval: interval fromDate: now];
    locNot.repeatInterval = freqFlag;
    [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
} else {
    for( int i = 1; i <= repeatCountDesired; ++i ) {
        locNot.fireDate = [NSDate dateWithTimeInterval: interval*i fromDate: now];
        [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
    }
}
[locNot release];

J'ai une idée comment faire, je l'ai mis en œuvre dans mon projet

Tout d'abord, créez une notification locale avec la date d'incendie (par exemple, toutes les minutes). L'étape suivante - remplissage informations utilisateur avec identifiant unique pour cette notification (si vous souhaitez supprimer à l'avenir) et votre période personnalisée comme ceci:

-(void) createLocalRepeatedNotificationWithId: (NSString*) Id
{

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    NSTimeInterval your_custom_fire_interval = 60; // interval in seconds
    NSDate *remindDate = [[NSDate date] dateByAddingTimeInterval:your_custom_fire_interval];
    localNotification.fireDate = remindDate;
    localNotification.userInfo = @{@"uid":Id, @"period": [NSNumber numberWithInteger:your_custom_fire_interval]};
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

Après cela, mettre en œuvre -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification dans votre AppDelegate:

  1. Fetch votre période personnalisée à partir d'informations utilisateur.
  2. Changer la date du feu pour la prochaine période
  3. Il suffit de l'ajouter dans les notificatiots sheluded à nouveau!

    NSInteger period = [[notification.userInfo objectForKey:@"period"] integerValue]; //1
    NSTimeInterval t= 10 * period;
    notification.fireDate =[[NSDate date] dateByAddingTimeInterval:t]; //2 
     [[UIApplication sharedApplication] scheduleLocalNotification:notification]; //3
    

si vous souhaitez supprimer cette notification, faire

UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
    UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
    NSDictionary *userInfoCurrent = oneEvent.userInfo;
    NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"id"]];
    if ([uid isEqualToString:notification_id_to_remove])
    {
        //Cancelling local notification
        [app cancelLocalNotification:oneEvent];
        break;
    }
}

Très important

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification ne pas appelé, quand tu fond. Donc, vous devez configurer la tâche d'arrière-plan en cours d'exécution longue, où vous allez créer à nouveau la notification.

Je l'ai utilisé ce code et il fonctionne très bien pour la répétition LocalNotification j'ai utilisé le code LavaSlider pour ce code Implémentation

     UILocalNotification *    localNotifEndCycle = [[UILocalNotification alloc] init];
      localNotifEndCycle.alertBody = @"Your Expected Date ";
      NSDate *now = [NSDate date];

      for( int i = 1; i <= 10;i++) 
     {
        localNotifEndCycle.alertBody = @"Your Expected Date ";
        localNotifEndCycle.soundName=@"best_guitar_tone.mp3";
        localNotifEndCycle.fireDate = [NSDate dateWithTimeInterval:180*i sinceDate:now];
        [[UIApplication sharedApplication] scheduleLocalNotification: localNotifEndCycle];
     }
     }
-(void)schedulenotificationfortimeinterval:(NSString *)id1
{
    NSLog(@"selected value %d",selectedvalue);

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MMM dd,yyyy hh:mm a"];

    UILocalNotification *localNotification2 = [[UILocalNotification alloc] init];


   // localNotification2. fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:0];

    if(selectedvalue==0)
    {
        NSLog(@"dk 0000");

        localNotification2.fireDate = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] ;//now

        localNotification2.applicationIconBadgeNumber = 1;

        localNotification2.repeatInterval=NSDayCalendarUnit;

    }
    if(selectedvalue==1)
    {
        NSLog(@"dk 1111");

        for( int u = 0; u <= 2 ;u++)
        {
        localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:43200.0*u] ;// 12 hr 
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 2;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }

     //  localNotification2.repeatInterval=NSDayCalendarUnit;

     }

    if(selectedvalue==2)
    {
        NSLog(@"dk 22222");
        for( int u = 0; u <= 3 ;u++)
        {
            localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:28800.0*u] ;//8 hr 
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 3;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }


      //  localNotification2.repeatInterval=NSDayCalendarUnit;
    }

    if(selectedvalue==3)
    {
       NSLog(@"dk 3333");
        for( int u = 0; u <= 4 ;u++)
        {
            localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:21600.0*u] ;//6 hr
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 4;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }


      //  localNotification2.repeatInterval=NSDayCalendarUnit;
   }  
 //   localNotification2.repeatInterval=NSDayCalendarUnit;

    NSLog(@"date is %@ %@",[MedicationDict valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]);

    localNotification2.timeZone = [NSTimeZone localTimeZone];


     localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

    localNotification2.alertAction = @"Notification";
    localNotification2.soundName=UILocalNotificationDefaultSoundName;
    //localNotification2.applicationIconBadgeNumber = 1;

  //  infoDict = [NSDictionary dictionaryWithObject:id1 forKey:@"did"];

  //  localNotification2.userInfo = infoDict;

  //  [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

 //   NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

   // [[UIApplication sharedApplication] cancelAllLocalNotifications];//dk
 }

Vous pouvez définir tout intervalle de temps que vous voulez, si vous configurez des notifications distinctes pour chaque fois que vous voulez une notification au feu. Vous devez ensuite les gérer, et si vous n'êtes pas une application qui est actuellement autorisé à courir en arrière-plan, vous devrez les rafraîchir en ayant l'utilisateur d'exécuter votre application pour le faire. Après avoir accompli cela, je peux vous dire qu'il est un PITA majeur.

//This is how I set local notification based on time interval repeatedly and executed method customized snooze and delete
let content = UNMutableNotificationContent()
content.title = "Time Based Local Notification"
content.subtitle = "Its is a demo"
content.sound = .default
content.categoryIdentifier = "UYLReminderCategory"

//repition of time base local notification in foreground, background, killed
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "IOS Demo", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "UYLDeleteAction", title: "Delete", options: [.destructive])
let cat = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction,deleteAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([cat])

notif.repeatInterval = NSDayCalendarUnit;

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top