我正在开发一个基于本地通知的 iPhone 报警应用程序。
删除警报时,相关的本地通知应被取消。但是如何确定要取消本地通知数组中的哪个对象呢?
我知道 [[UIApplication sharedApplication] cancelLocalNotification:notification]
方法,但我怎样才能得到这个“通知”来取消它?
最佳答案
您可以在本地通知的用户信息中保存唯一的键值。 获取所有本地通知,遍历数组并删除特定通知。
代码如下,
OBJ-C:
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:@"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
SWIFT:
var app:UIApplication = UIApplication.sharedApplication()
for oneEvent in app.scheduledLocalNotifications {
var notification = oneEvent as UILocalNotification
let userInfoCurrent = notification.userInfo! as [String:AnyObject]
let uid = userInfoCurrent["uid"]! as String
if uid == uidtodelete {
//Cancelling local notification
app.cancelLocalNotification(notification)
break;
}
}
用户通知:
如果您使用 UserNotification (iOS 10+),请按照以下步骤操作:
在创建 UserNotification 内容时,添加唯一的 identifier
使用 removePendingNotificationRequests(withIdentifiers:) 删除特定的待处理通知
使用 removeDeliveredNotifications(withIdentifiers:) 删除特定的已发送通知
欲了解更多信息,UNUserNotificationCenter
关于objective-c - 删除特定的本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340664/