取消 UILocalNotification

发布于 2024-09-07 19:24:59 字数 1335 浏览 3 评论 0原文

我的 UILocalNotification 有问题。

我正在用我的方法安排通知。

- (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];
}

它工作正常,我正确地收到了通知。问题是我什么时候应该取消通知。我正在使用这个方法。

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

我不确定在这里做什么,但我的问题是:

我如何知道应该删除哪个 UILocalNotification 对象?
有没有办法列出所有通知?

我唯一拥有的就是我应该删除哪个提醒的 ID。
我正在考虑将 UILocalNotification 对象保存在我的“Note”对象中并以这种方式获取它,当我保存到 SQLite 数据库时序列化该对象等等......有没有更聪明的方法?

I have a problem with my UILocalNotification.

I am scheduling the notification with my method.

- (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];
}

Its work fine and I'm correctly receiving the notification. The problem is when I should cancel the notification. Im using this method.

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

Im not sure what to do here, but my questions are:

How do I know which UILocalNotification object I should delete?
Is there a way to list all notifications?

The only thing I have is the ID of which reminder I should delete.
I was thinking about to save the UILocalNotification object in my "Note" object and get it that way, and when I saving to my SQLite database serialize the object and so on ... is there a smarter way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

诗笺 2024-09-14 19:25:00

斯威夫特5:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: arrayContainingIdentifiers)

Swift 5:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: arrayContainingIdentifiers)
美人如玉 2024-09-14 19:25:00

在 swift 中,您首先通过以下方式向通知 userInfo 添加一个字典:

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

然后,您想要获取现有通知的数组 (2),并迭代每个通知 (3),直到找到您要查找的通知。找到后,将其取消 (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)
                }
            }
        }
    }
}

In swift, you first add a dict to notifications userInfo by:

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

Then, you want to get an array of existing notifications (2), and iterate through each one (3) until you find the one you're looking for. Once you find it, cancel it (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)
                }
            }
        }
    }
}
痕至 2024-09-14 19:25:00

Swift 版本:

UIApplication.sharedApplication().cancelAllLocalNotifications()

Swift version:

UIApplication.sharedApplication().cancelAllLocalNotifications()
木森分化 2024-09-14 19:25:00

使用用户信息取消特定“本地通知”的 Swift 版本:

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!")
            }
        }
    }

Swift version to cancel particular "Local Notification" using 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!")
            }
        }
    }
东京女 2024-09-14 19:25:00

我的解决方案是删除这些方法上的所有计划通知。

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

[[UIApplication共享应用程序]cancelAllLocalNotifications];

您仍然可以使用以下方式访问激活您的应用程序的 LocalNotification 对象。

    UILocalNotification *localNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];

然后我重新安排新的通知,

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

这避免了对所有通知进行簿记。我还在 userInfo 字典中发送一些上下文信息。这有助于跳转到应用程序中的正确位置。

My solution is to remove all scheduled Notifications on these methods.

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

with

[[UIApplication sharedApplication] cancelAllLocalNotifications];

You can still get to the LocalNotification object that activated your app by using.

    UILocalNotification *localNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];

Then I reschedule new Notifications on

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

This avoids to have bookkeeping for all the notifications. I send some context information in the userInfo dictionary as well. This then helps to jump to the right place in the app.

抽个烟儿 2024-09-14 19:25:00

感谢@viggio24的好回答,这是一个快速版本

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++
}

Thank @viggio24 for the good answer, this is a swift version

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++
}
千仐 2024-09-14 19:24:59

我的解决方案是使用 UILocalNotification userInfo 字典。事实上,我所做的是为我的每个通知生成一个唯一ID(当然这个ID是我稍后可以检索到的),然后当我想要时要取消与给定 ID 关联的通知,我只需使用数组扫描所有可用的通知:

[[UIApplication sharedApplication] scheduledLocalNotifications]

然后尝试通过调查 ID 来匹配通知。例如:


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];

我不知道这种方法相对于归档/取消归档方法是否更好,但它有效并将数据限制为仅保存为 ID。

编辑:缺少一个刹车

My solution is to use the UILocalNotification userInfo dictionary. In fact what I do is to generate a unique ID for each of my notifications (of course this ID is something I'm able to retrieve later), then when I want to cancel the notification associated to a given ID I will simply scan all available notifications using the array:

[[UIApplication sharedApplication] scheduledLocalNotifications]

and then I try to match the notifications by investigating the ID. E.g.:


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];

I don't know if this approach is better or not with respect to the Archiving/Unarchving one, however it works and limits data to be saved to just an ID.

Edit: there was a missing braket

别念他 2024-09-14 19:24:59

您可以从 scheduledLocalNotifications 或者您可以将它们全部取消:

  [[UIApplication sharedApplication] cancelAllLocalNotifications];

You can get a list of all scheduled notifications from scheduledLocalNotifications or you can cancel them all:

  [[UIApplication sharedApplication] cancelAllLocalNotifications];
迷爱 2024-09-14 19:24:59

我的解决方案是存档您使用 NSKeyedArchiver 安排的 UILocalNotification 对象并将其存储在某个地方(首选 plist 中)。然后,当您想要取消通知时,查找 plist 中的正确数据并使用 NSKeyedUnarchiver 取消存档。
代码非常简单:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notice];

并且

UILocalNotification *notice = [NSKeyedUnarchiver unarchiveObjectWithData:data];

My solution is to archive UILocalNotification object you have scheduled with NSKeyedArchiver and store it somewhere (in a plist is preferred). And then, when you want to to can cancel the notification, look up the plist for the correct data and use NSKeyedUnarchiver to unarchive.
The code is pretty easy:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notice];

and

UILocalNotification *notice = [NSKeyedUnarchiver unarchiveObjectWithData:data];
污味仙女 2024-09-14 19:24:59

我的解决方案是,当您创建 UILocalNotification 时,您创建一个 NSMutableDictionary 并将该通知存储为键值作为您的 ID,然后将此 NSMutableDictionay 放入code> 到你的 NSUserDefaults

因此,当你想取消任何特定的本地通知时,你可以写
[dictionary valueforkey @"KEY"] 作为密钥,您传递您的 id,以便获得特定的本地通知并将其传递给

 [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 

My solution is you when you create UILocalNotification at that time you create one NSMutableDictionary and store that notification as a value for key as your ID and put this NSMutableDictionay to your NSUserDefaults

So when you want to cancel any particular localnotification at that time you write
[dictionary valueforkey @"KEY"] where as a key you pass your id so you get that particular local notification and pass it to

 [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文