web-dev-qa-db-fra.com

Annuler UILocalNotification

J'ai un problème avec mon UILocalNotification.

Je planifie la notification avec ma méthode.

- (void) sendNewNoteLocalReminder:(NSDate *)date  alrt:(NSString *)title
{
    // some code ...
    UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 

    if (localNotif == nil)  
        return;

    localNotif.fireDate = itemDate; 
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.alertAction = NSLocalizedString(@"View Details", nil); 
    localNotif.alertBody = title;
    localNotif.soundName = UILocalNotificationDefaultSoundName; 
    localNotif.applicationIconBadgeNumber = 0;

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:stringID forKey:@"id"]; 
    localNotif.userInfo = infoDict; 

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
    [localNotif release];
}

Son travail fonctionne bien et je reçois correctement la notification. Le problème est quand je devrais annuler la notification. J'utilise cette méthode.

- (void) deleteNewNoteLocalReminder:(NSString*) reminderID noteIDe:(NSInteger)noteIDE
{
    [[UIApplication sharedApplication] cancelLocalNotification:(UILocalNotification *)notification ????  
}

Je ne sais pas quoi faire ici, mais mes questions sont:

Comment savoir quel objet UILocalNotification dois-je supprimer?
Existe-t-il un moyen de répertorier toutes les notifications?

La seule chose que j'ai, c'est l'ID dont je dois supprimer le rappel.
Je pensais à enregistrer l'objet UILocalNotification dans mon objet "Note" et l'obtenir de cette façon, et quand j'enregistre dans ma base de données SQLite sérialiser l'objet, etc.

47
f0rz

Swift 5:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: arrayContainingIdentifiers)
1
Mostafa ElShazly

Ma solution consiste à utiliser le dictionnaire UILocalNotification userInfo . En fait, ce que je fais, c'est de générer un identifiant unique pour chacune de mes notifications (bien sûr cela [~ # ~] id [~ # ~] est quelque chose que je peux récupérer plus tard), puis quand je veux annuler la notification associée à une donnée [ ~ # ~] id [~ # ~] Je vais simplement scanner toutes les notifications disponibles en utilisant le tableau:

[[UIApplication sharedApplication] scheduledLocalNotifications]

puis j'essaie de faire correspondre les notifications en recherchant [~ # ~] id [~ # ~] . Par exemple.:


NSString *myIDToCancel = @"some_id_to_cancel";
UILocalNotification *notificationToCancel=nil;
for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
  if([[aNotif.userInfo objectForKey:@"ID"] isEqualToString:myIDToCancel]) {
     notificationToCancel=aNotif;
     break;
  }
}
if(notificationToCancel) [[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

Je ne sais pas si cette approche est meilleure ou non par rapport à celle d'archivage/désarchivage, mais elle fonctionne et limite les données à enregistrer à un simple ID.

Edit: il manquait un braket

93
viggio24

Vous pouvez obtenir une liste de toutes les notifications planifiées à partir de scheduleLocalNotifications ou vous pouvez toutes les annuler:

  [[UIApplication sharedApplication] cancelAllLocalNotifications];
57
progrmr

Ma solution est d'archiver l'objet UILocalNotification que vous avez planifié avec NSKeyedArchiver et de le stocker quelque part (dans un plist est préférable). Et puis, lorsque vous le souhaitez, vous pouvez annuler la notification, recherchez dans le plist les données correctes et utilisez NSKeyedUnarchiver pour désarchiver. Le code est assez simple:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notice];

et

UILocalNotification *notice = [NSKeyedUnarchiver unarchiveObjectWithData:data];
13
hiepnd

Ma solution est de vous lorsque vous créez UILocalNotification à ce moment-là, vous en créez un NSMutableDictionary et stockez cette notification comme valeur pour la clé comme votre ID et mettez ce NSMutableDictionay dans votre NSUserDefaults

Ainsi, lorsque vous souhaitez annuler une notification locale particulière à ce moment, vous écrivez [dictionary valueforkey @"KEY"] où, en tant que clé, vous transmettez votre identifiant pour obtenir cette notification locale particulière et la transmettre à

 [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
6
Mahek

Dans Swift, vous ajoutez d'abord un dict aux notifications userInfo en:

let dict:NSDictionary = ["ID" : "someString"]
notification.userInfo = dict as! [String : String]

Ensuite, vous souhaitez obtenir un tableau de notifications existantes (2) et parcourir chacune (3) jusqu'à ce que vous trouviez celle que vous recherchez. Une fois que vous l'avez trouvé, annulez-le (4).

// 1. Pass in the string you want to cancel
func cancelLocalNotification(uniqueId: String){

    // 2. Create an array of notifications, ensuring to use `if let` so it fails gracefully
    if let notifyArray = UIApplication.sharedApplication().scheduledLocalNotifications {

        // 3. For each notification in the array ...
        for notif in notifyArray as [UILocalNotification] {
            // ... try to cast the notification to the dictionary object
            if let info = notif.userInfo as? [String: String] {

                // 4. If the dictionary object ID is equal to the string you passed in ...
                if info["ID"] == uniqueId {
                    // ... cancel the current notification
                    UIApplication.sharedApplication().cancelLocalNotification(notif)
                }
            }
        }
    }
}
3
bwash70

Swift version:

UIApplication.sharedApplication().cancelAllLocalNotifications()
2
fatihyildizhan

Version Swift pour annuler une "notification locale" particulière en utilisant userinfo .:

func cancelLocalNotification(UNIQUE_ID: String){

        var notifyCancel = UILocalNotification()
        var notifyArray = UIApplication.sharedApplication().scheduledLocalNotifications

        for notifyCancel in notifyArray as! [UILocalNotification]{

            let info: [String: String] = notifyCancel.userInfo as! [String: String]

            if info[uniqueId] == uniqueId{

                UIApplication.sharedApplication().cancelLocalNotification(notifyCancel)
            }else{

                println("No Local Notification Found!")
            }
        }
    }
1
Sohil R. Memon

Merci @ viggio24 pour la bonne réponse, ceci est une version Swift

var notifyCancel = UILocalNotification()
var notifyArray=UIApplication.sharedApplication().scheduledLocalNotifications
var i = 0
while(i<notifyArray.count){
    if let notify = notifyArray[i] as? UILocalNotification{
        if let info = notify.userInfo as? Dictionary<String,String> {
            if let s = info["name"] {
                if(name==s){//name is the the one you want cancel
                    notifyCancel = notify
                    break
                }
            }
        }
    }
i++
}
0
王怡飞

Ma solution consiste à supprimer toutes les notifications planifiées sur ces méthodes.

-applicationDidFinishLaunchingWithOptions: 
- (void)applicationDidBecomeActive:(UIApplication *)application;
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;

avec

[[UIApplication sharedApplication] cancelAllLocalNotifications];

Vous pouvez toujours accéder à l'objet LocalNotification qui a activé votre application à l'aide de.

    UILocalNotification *localNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];

Ensuite, je replanifie de nouvelles notifications sur

- (void)applicationDidEnterBackground:(UIApplication *)application;

Cela évite d'avoir une comptabilité pour toutes les notifications. J'envoie également des informations contextuelles dans le dictionnaire userInfo. Cela permet ensuite de sauter au bon endroit dans l'application.

0
orkoden