Ответ 1
UIApplication
имеет свойство scheduledLocalNotifications
, которое вы можете использовать.
Мое приложение позволяет пользователям устанавливать количество напоминаний в будущем. Когда приложение lauches я хочу знать, какие напоминания (уведомления) уже установлены.
Могу ли я прочитать уведомления, которые я установил или мне нужно сохранить в своем приложении (например, Core Data или Plist)?
UIApplication
имеет свойство scheduledLocalNotifications
, которое вы можете использовать.
UIApplication
свойство scheduledLocalNotifications
Здесь код:
NSMutableArray *notifications = [[NSMutableArray alloc] init];
[notifications addObject:notification];
app.scheduledLocalNotifications = notifications;
//Equivalent: [app setScheduledLocalNotifications:notifications];
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;
}
}
NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
if ([localNotification.alertBody isEqualToString:savedTitle]) {
NSLog(@"the notification this is canceld is %@", localNotification.alertBody);
[[UIApplication sharedApplication] cancelLocalNotification:localNotification] ; // delete the notification from the system
}
}
Для получения дополнительной информации ознакомьтесь с этим: scheduleLocalNotifications пример IIApplication ios
Для Swift 3.0
let center = UNUserNotificationCenter.current()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
center.getPendingNotificationRequests { (notifications) in
print("Count: \(notifications.count)")
for item in notifications {
print(item.content)
}
}
}
@Скотт Берревовец дал правильный ответ. Чтобы фактически перечислить их, просто перечислить объекты в массиве:
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(UILocalNotification *notification, NSUInteger idx, BOOL *stop) {
NSLog(@"Notification %lu: %@",(unsigned long)idx, notification);
}];
Swift 3.0.2:
UIApplication.shared.scheduledLocalNotifications
В Swift, чтобы просмотреть все текущие запланированные локальные уведомления, напечатанные на консоли:
print(UIApplication.sharedApplication().scheduledLocalNotifications)
В iOS 10
, используя новую структуру UserNotifications
:
UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
print("Requests: \(notificationRequest)")
}
Swift 4
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in
for request in requests {
if request.identifier == "IDENTIFIER YOU'RE CHECKING IF EXISTS" {
//Notification already exists. Do stuff.
} else if request === requests.last {
//All requests have already been checked and notification with identifier wasn't found. Do stuff.
}
}
})
Я использовал это, чтобы исправить ошибку, когда одно и то же еженедельное уведомление уже было установлено и было установлено снова, когда приложение откроется, поэтому он будет продолжать сброс таймера, что означает, что он никогда не появлялся.