Tôi đang làm cho các ứng dụng có nhu cầu thiết lập thông báo, may mắn tôi đã có thể thiết lập các thông báo địa phương nhưng tôi không biết làm thế nào để xóa các thông báo được thiết lập bởi ứng dụng này (của tôi aplicaton) .Xcode không cung cấp chức năng xóa bằng removeAllNotifications nhưng bạn không thể xóa các thông báo đã chọn được thiết lập bởi ứng dụnglàm thế nào để hủy bỏ một thông báo địa phương trong iphone
Trả lời
Bạn có thể gọi [[UIApplication sharedApplication] cancelLocalNotification:notification]
để hủy thông báo. Vì thông báo cục bộ tuân theo giao thức NSCoding
, chúng có thể được lưu trữ và truy xuất để hủy sau này.
thansk cho các đầu vào của bạn nhưng tôi nên thêm thông báo gì vào mehtod [UIApplicationsharedApplication] cancelLocalNotification: notification] cảm ơn lại – mrugen
Vâng, bạn phải tạo đối tượng thông báo tại một số thời điểm để lên lịch, ! Khi bạn đã tạo đối tượng thông báo, bạn có thể lưu nó vào đĩa bằng giao thức NSCoding và tải lại sau (tức là lần khởi chạy ứng dụng tiếp theo) để hủy sau này. –
Tôi biết bài này là cũ nhưng hy vọng giải pháp này sẽ giúp người
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for(UILocalNotification *notification in notificationArray){
if ([notification.alertBody isEqualToString:@"your alert body"] && (notification.fireDate == your alert date time)) {
// delete this notification
[[UIApplication sharedApplication] cancelLocalNotification:notification] ;
}
}
tôi so sánh cơ thể và ngày thời gian tỉnh táo chỉ để chắc chắn rằng tôi đang xóa thông báo ngay từ khi có những cơ hội mà hai hay nhiều thông báo hơn có thể có cùng thời gian hoặc cảnh báo.
Mẹo hay, Cảm ơn @NSDumb – Yossi
Bạn nên sử dụng 'isEqualToDate:' thay vì '=='. –
Thông báo địa phương trong iOS 10 và Dưới iOS 10 với Xcode 8 beta 2
pragma mark - Tính Trước ngày
-(void) calculateBeforedays:(int)_day hours:(int)_hours minutes:(int) _minutes { //_fir:(int)_firecount
//Get Predefined Future date
NSString *dateString = [NSString stringWithFormat:@"%@T%@:00.000Z",_eventdate,_eventtime];
NSLog(@"dateString %@",dateString);
// NSLog(@"_firecount %d",_firecount);
// //Get Predefined Future date
// NSString *dateString = [NSString stringWithFormat:@"2016-12-31T12:%d:00.000Z",_firecount];
// NSLog(@"dateString %@",dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate *marrigeDate = [dateFormatter dateFromString:dateString];
// Set reminder date before marrige date
int setDay = _day;
int setHours = _hours;
int setMins = _minutes;
float milliseconds = (setDay * 24 * 60 * 60) + (setHours * 60 * 60) + (setMins * 60);
NSDate *someDateInUTC = [NSDate date];
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
//Get Current date
NSDate *currentDate = dateInLocalTimezone;
NSTimeInterval marigeTimeInterval = [marrigeDate timeIntervalSinceDate:currentDate];
//Get difference between time
NSTimeInterval timeIntervalCountDown = marigeTimeInterval - milliseconds;
//Set perticulater timer
NSDate *timerDate = [NSDate dateWithTimeIntervalSinceNow:timeIntervalCountDown];
[self triggerNotification:timerDate];
}
#pragma mark- Trigger Reminders
- (void)triggerNotification:(NSDate *) reminderDate {
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
// create actions
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// create actions
UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:@"com.inviteapp.yes"
title:@"Accept"
options:UNNotificationActionOptionForeground];
UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"com.inviteapp.no"
title:@"Decline"
options:UNNotificationActionOptionDestructive];
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:@"com.inviteapp.snooze"
title:@"Snooze"
options:UNNotificationActionOptionDestructive];
NSArray *notificationActions = @[ acceptAction, declineAction, snoozeAction ];
// create a category
UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier actions:notificationActions intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:inviteCategory];
// registration
[center setNotificationCategories:categories];
#endif
}
else if([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0f){
// create actions
UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = @"com.inviteapp.yes";
acceptAction.title = @"Accept";
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO; //If YES requies passcode, but does not unlock the device
UIMutableUserNotificationAction *declineAction = [[UIMutableUserNotificationAction alloc] init];
declineAction.identifier = @"com.inviteapp.no";
acceptAction.title = @"Decline";
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
declineAction.destructive = YES;
acceptAction.authenticationRequired = NO;
UIMutableUserNotificationAction *snoozeAction = [[UIMutableUserNotificationAction alloc] init];
snoozeAction.identifier = @"com.inviteapp.snooze";
acceptAction.title = @"Snooze";
snoozeAction.activationMode = UIUserNotificationActivationModeBackground;
snoozeAction.destructive = YES;
snoozeAction.authenticationRequired = NO;
// create a category
UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = CYLInviteCategoryIdentifier;
NSArray *notificationActions = @[ acceptAction, declineAction, snoozeAction ];
[inviteCategory setActions:notificationActions forContext:UIUserNotificationActionContextDefault];
[inviteCategory setActions:notificationActions forContext:UIUserNotificationActionContextMinimal];
// registration
NSSet *categories = [NSSet setWithObject:inviteCategory];
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
/// 2. request authorization for localNotification
[self registerNotificationSettingsCompletionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
[self localNotificationForiOS10:reminderDate];
#endif
} else {
[self localNotificationBelowiOS10: reminderDate];
}
}
- (void)registerNotificationSettingsCompletionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler; {
/// 2. request authorization for localNotification
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:completionHandler];
#endif
} else if([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0f){
UIUserNotificationSettings *userNotificationSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge)
categories:nil];
UIApplication *application = [UIApplication sharedApplication];
[application registerUserNotificationSettings:userNotificationSettings];
}
}
để thiết lập nhiều thông báo: iOS 10, thêm khác nhau requestWithIdentifier
pragma mark- Locanotification nhiều hơn iOS 10
-(void) localNotificationForiOS10:(NSDate *) _reminderDate{
_eventReminderDate = _reminderDate;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:_reminderDate];
NSLog(@"NSDateComponents %@",components);
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:_eventname arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"You have event reminder"
arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"eventdate"
content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"Local Notification succeeded");
}
else {
NSLog(@"Local Notification failed");
}
}];
}
để thiết lập nhiều thông báo bên dưới iOS 10, thêm khác nhau UserInfo
pragma mark- Locanotification ít hơn iOS 10
-(void) localNotificationBelowiOS10:(NSDate *) _reminderDate{
_eventReminderDate = _reminderDate;
NSLog(@"dateInLocalTimezone %@",_eventReminderDate);
/// 3. schedule localNotification
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = _eventReminderDate ;
localNotification.alertTitle = _eventname;
localNotification.alertBody = @"You have Event Name";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = 0;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSDictionary *info = [NSDictionary dictionaryWithObject:_eventname forKey:_eventname];
localNotification.userInfo = info;
NSLog(@"info ---- %@",info);
NSLog(@"notification userInfo gets name : %@",[info objectForKey:_eventname]);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
pragma mark- Xóa Perticulater Thông báo địa phương
-(IBAction)deleteReminder:(id)sender{
UIButton *senderButton = (UIButton *)sender;
_selectedRow = senderButton.tag;
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:senderButton.tag inSection:0]; // if section is 0
ReminderCell * cell = (ReminderCell*)[_tableView cellForRowAtIndexPath:indexPath];
_eventname = [[_eventArray objectAtIndex:indexPath.row] objectForKey:@"event_name"];
_eventdate = [[_eventArray objectAtIndex:indexPath.row] objectForKey:@"event_date"];
_eventtime = [[_eventArray objectAtIndex:indexPath.row] objectForKey:@"event_st"];
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// remove all local notification:
[center removePendingNotificationRequestsWithIdentifiers:@[_eventname]];
#endif
} else {
NSLog(@"Delete notification below ios 10");
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 *ename=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:_eventname]];
if ([ename isEqualToString:_eventname])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
}
- 1. IOS Hủy Thông báo Địa phương
- 2. iPhone: thông báo địa phương Daily
- 3. Cập nhật ngày cháy để thông báo địa phương và hủy thông báo trước
- 4. Làm thế nào để bỏ/Hủy bỏ thông báo trên thanh trạng thái ở android trình
- 5. iPhone làm thế nào để hủy bỏ stop performSelector
- 6. Hủy thông báo địa phương không hoạt động
- 7. Làm thế nào để hủy bỏ một jquery.load()?
- 8. Lịch biểu số thông báo địa phương
- 9. Gửi thông báo địa phương trong Android
- 10. Làm cách nào để hủy bỏ Báo cáo tinh thể
- 11. Làm thế nào để hủy bỏ NSBlockOperation
- 12. Làm thế nào để khai báo một luồng địa phương tĩnh trong một mẫu
- 13. Làm thế nào để hủy bỏ một UIWebView?
- 14. Làm thế nào để hủy bỏ BroadcastReceiver trong android
- 15. Làm thế nào để hủy bỏ một quá trình PHP, khi cuộc gọi ajax bị hủy?
- 16. Xóa số huy hiệu khi thông báo địa phương bị hủy
- 17. Region dựa thông báo địa phương
- 18. thông báo địa phương tại Foreground
- 19. Làm thế nào để hủy bỏ một nỗ lực kết nối TSQLConnection trong XE2?
- 20. Làm thế nào hủy bỏ việc thực hiện một SwingWorker?
- 21. Làm thế nào để AppDomain.Unload() hủy bỏ các chủ đề?
- 22. Làm thế nào để loại bỏ một repo Git địa phương từ TortoiseGit?
- 23. làm thế nào để loại bỏ git thay đổi chi nhánh địa phương?
- 24. Làm thế nào để loại bỏ một hiện vật dự án từ repo maven địa phương?
- 25. Thông báo địa phương ngẫu nhiên trong nền
- 26. Làm thế nào để bạn hủy bỏ một jQuery fadeOut() một khi nó đã bắt đầu?
- 27. Tôi làm cách nào để lên lịch thông báo địa phương cho kịch bản sau?
- 28. Làm thế nào để loại bỏ một thông báo pynotify lỗi thời?
- 29. Làm thế nào để hiểu được phương thức chờ và thông báo trong Java Thread?
- 30. Cách tăng số hiệu ứng dụng cho thông báo địa phương định kỳ (iPhone)
Bạn có thể tìm thấy câu trả lời của bạn ở đây: http://stackoverflow.com/questions/3158264/cancel-uilocalnotification/ 3334028 – hiepnd