특정 로컬 알림 삭제
저는 로컬 알림을 기반으로 아이폰 알람 앱을 개발하고 있습니다.
알람을 삭제하면 관련 로컬 알림이 취소됩니다.그러나 로컬 알림 배열에서 취소할 개체를 정확히 결정하려면 어떻게 해야 합니까?
는 알고 있습니다.[[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;
}
}
스위프트:
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;
}
}
사용자 알림:
사용자 알림(iOS 10+)을 사용하는 경우 다음 단계를 수행합니다.
사용자 알림 콘텐츠를 만들 때 고유 식별자 추가
removePendingNotificationRequests(식별자 포함)를 사용하여 보류 중인 특정 알림을 제거합니다.
자세한 내용은 UN 사용자 알림 센터
기타 옵션:
때에 사용할 수 할 수 . 기본값에 할 수 . 이, 먼저로알생을때성할사나사수저있할기습니다장에값있수본용자할용에록도중컬림▁first▁needs▁first있수다니습▁then▁defaults▁and▁use▁this▁in▁it▁not▁when▁can,▁for저할d먼▁local▁future▁local,ification▁defaults▁you,장저▁be▁store,에▁you기값▁user,▁ns▁not▁into▁can▁object▁to▁create▁converted,ification본▁object사로있수▁directly 로컬 알림 개체는 사용자 기본값에 직접 저장할 수 없습니다. 이 개체를 먼저 NSData 개체로 변환한 다음NSData
다수있니에 할 수 .User defaults
다음은 이를 위한 코드입니다.
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:localNotif];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
로컬 알림을 저장하고 예약한 후에는 이전에 생성한 알림을 취소해야 하므로 사용자 기본값에서 해당 알림을 검색할 수 있습니다.
NSData *data= [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%d",UniqueKey]];
UILocalNotification *localNotif = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"Remove localnotification are %@", localNotif);
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%d",UniqueKey]];
이것이 도움이 되기를 바랍니다.
제가 하는 일은 이렇습니다.
알림을 생성할 때 다음 작업을 수행합니다.
// Create the notification
UILocalNotification *notification = [[UILocalNotification alloc] init] ;
notification.fireDate = alertDate;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertAction = NSLocalizedString(@"Start", @"Start");
notification.alertBody = **notificationTitle**;
notification.repeatInterval= NSMinuteCalendarUnit;
notification.soundName=UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;
삭제를 시도할 때는 다음을 수행합니다.
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
}
}
이 솔루션은 여러 알림에 사용할 수 있으며 어레이, 사전 또는 사용자 기본값을 관리하지 않습니다.이미 시스템 알림 데이터베이스에 저장한 데이터를 사용하기만 하면 됩니다.
이것이 미래의 디자이너와 개발자들에게 도움이 되기를 바랍니다.
해피 코딩 여러분! :D
신속한 알림 예약 및 제거:
static func scheduleNotification(notificationTitle:String, objectId:String) {
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 24*60*60)
localNotification.alertBody = notificationTitle
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = 1
//play a sound
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertAction = "View"
var infoDict : Dictionary<String,String!> = ["objectId" : objectId]
localNotification.userInfo = infoDict;
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
static func removeNotification(objectId:String) {
var app:UIApplication = UIApplication.sharedApplication()
for event in app.scheduledLocalNotifications {
var notification = event as! UILocalNotification
var userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
var infoDict : Dictionary = notification.userInfo as! Dictionary<String,String!>
var notifcationObjectId : String = infoDict["objectId"]!
if notifcationObjectId == objectId {
app.cancelLocalNotification(notification)
}
}
}
Swift 4 솔루션:
UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
for request in requests {
if request.identifier == "identifier" {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["identifier"])
}
}
}
iMOBDEV의 솔루션은 특정 알림을 제거하는 데 완벽하게 작동하지만(예: 알람 삭제 후), 이미 실행되어 알림 센터에 남아 있는 알림을 선택적으로 제거해야 할 때 특히 유용합니다.
가능한 시나리오는 경보 알림이 실행되지만 사용자는 해당 알림을 누르지 않고 앱을 열고 해당 경보를 다시 예약하는 것입니다.지정된 항목/알람에 대해 알림 센터에 하나의 알림만 표시되도록 하려면 이 방법이 좋습니다.또한 앱을 열 때마다 모든 알림을 지울 필요가 없습니다. 앱에 더 잘 맞을 것입니다.
- 알림을 는 로컬알생때사용을 합니다.
NSKeyedArchiver
을 로저하기위로 하기 위해Data
UserDefaults
알림의 userInfo 사전에 저장 중인 것과 동일한 키를 만들 수 있습니다.객체와 인 Core Data 객체를 할 수 .ID 속성. - 사하여색으로 합니다.
NSKeyedUnarchiver
이제 로컬 알림 취소 방법을 사용하여 삭제할 수 있습니다. - 에서 합니다.
UserDefaults
따라서.
다음은 해당 솔루션의 Swift 3.1 버전(iOS 10 이하 대상)입니다.
가게
// localNotification is the UILocalNotification you've just set up
UIApplication.shared.scheduleLocalNotification(localNotification)
let notificationData = NSKeyedArchiver.archivedData(withRootObject: localNotification)
UserDefaults.standard.set(notificationData, forKey: "someKeyChosenByYou")
검색 및 삭제
let userDefaults = UserDefaults.standard
if let existingNotificationData = userDefaults.object(forKey: "someKeyChosenByYou") as? Data,
let existingNotification = NSKeyedUnarchiver.unarchiveObject(with: existingNotificationData) as? UILocalNotification {
// Cancel notification if scheduled, delete it from notification center if already delivered
UIApplication.shared.cancelLocalNotification(existingNotification)
// Clean up
userDefaults.removeObject(forKey: "someKeyChosenByYou")
}
필요한 경우 빠른 버전:
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!")
}
}
}
알림을 예약할 때 카테고리 식별자가 있는 문자열을 유지할 수 있습니다.
localNotification.category = NotificationHelper.categoryIdentifier
그리고 그것을 검색하고 그렇게 필요할 때 취소합니다.
let app = UIApplication.sharedApplication()
for notification in app.scheduledLocalNotifications! {
if let cat = notification.category{
if cat==NotificationHelper.categoryIdentifier {
app.cancelLocalNotification(notification)
break
}
}
}
신속한 3-스타일:
final private func cancelLocalNotificationsIfIOS9(){
//UIApplication.shared.cancelAllLocalNotifications()
let app = UIApplication.shared
guard let notifs = app.scheduledLocalNotifications else{
return
}
for oneEvent in notifs {
let notification = oneEvent as UILocalNotification
if let userInfoCurrent = notification.userInfo as? [String:AnyObject], let uid = userInfoCurrent["uid"] as? String{
if uid == uidtodelete {
//Cancelling local notification
app.cancelLocalNotification(notification)
break;
}
}
}
}
iOS 10의 경우:
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [uidtodelete])
는 "UILocalNotification"입니다.cancelLocalNotification:
기존 UILocalNotification 개체와 일치하는 속성이 일치합니다.
그래서:
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"foo";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
에서는 나중에 다음을 통해 취소할 수 있는 로컬 알림을 표시합니다.
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"foo";
[[UIApplication sharedApplication] cancelLocalNotification:notification];
Swift 2.0에서 이 기능을 사용합니다.
static func DeleteNotificationByUUID(uidToDelete: String) -> Bool {
let app:UIApplication = UIApplication.sharedApplication()
// loop on all the current schedualed notifications
for schedualedNotif in app.scheduledLocalNotifications! {
let notification = schedualedNotif as UILocalNotification
let urrentUi = notification.userInfo! as! [String:AnyObject]
let currentUid = urrentUi["uid"]! as! String
if currentUid == uidToDelete {
app.cancelLocalNotification(notification)
return true
}
}
return false
}
@King of Bliss의 대답에서 영감을 받았습니다.
반복 알림의 경우(예를 들어, 일요일, 토요일, 수요일 오후 4시에 알람을 울리려면 알람을 3개 만들고 반복을 설정해야 합니다.NSWeekCalendarUnit)에 대한 간격입니다.
한 번만 주의사항을 작성하는 경우:
UILocalNotification *aNotification = [[UILocalNotification alloc] init];
aNotification.timeZone = [NSTimeZone defaultTimeZone];
aNotification.alertBody = _reminderTitle.text;
aNotification.alertAction = @"Show me!";
aNotification.soundName = UILocalNotificationDefaultSoundName;
aNotification.applicationIconBadgeNumber += 1;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: _reminderDate];
[componentsForFireDate setHour: [componentsForFireDate hour]] ; //for fixing 8PM hour
[componentsForFireDate setMinute:[componentsForFireDate minute]];
[componentsForFireDate setSecond:0] ;
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
aNotification.fireDate = fireDateOfNotification;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:_reminderTitle.text forKey:kRemindMeNotificationDataKey];
aNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:aNotification];
반복 주의사항 작성:
for (int i = 0 ; i <reminderDaysArr.count; i++)
{
UILocalNotification *aNotification = [[UILocalNotification alloc] init];
aNotification.timeZone = [NSTimeZone defaultTimeZone];
aNotification.alertBody = _reminderTitle.text;
aNotification.alertAction = @"Show me!";
aNotification.soundName = UILocalNotificationDefaultSoundName;
aNotification.applicationIconBadgeNumber += 1;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: _reminderDate];
[componentsForFireDate setWeekday: [[reminderDaysArr objectAtIndex:i]integerValue]];
[componentsForFireDate setHour: [componentsForFireDate hour]] ; // Setup Your Own Time.
[componentsForFireDate setMinute:[componentsForFireDate minute]];
[componentsForFireDate setSecond:0] ;
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
aNotification.fireDate = fireDateOfNotification;
aNotification.repeatInterval = NSWeekCalendarUnit;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:_reminderTitle.text forKey:kRemindMeNotificationDataKey];
aNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:aNotification];
}
}
필터링의 경우 배열을 사용하여 표시합니다.
-(void)filterNotficationsArray:(NSMutableArray*) notificationArray{
_dataArray = [[NSMutableArray alloc]initWithArray:[[UIApplication sharedApplication] scheduledLocalNotifications]];
NSMutableArray *uniqueArray = [NSMutableArray array];
NSMutableSet *names = [NSMutableSet set];
for (int i = 0 ; i<_dataArray.count; i++) {
UILocalNotification *localNotification = [_dataArray objectAtIndex:i];
NSString * infoDict = [localNotification.userInfo objectForKey:@"kRemindMeNotificationDataKey"];
if (![names containsObject:infoDict]) {
[uniqueArray addObject:localNotification];
[names addObject:infoDict];
}
}
_dataArray = uniqueArray;
}
한 번만 또는 반복된 경우에도 주의사항을 제거하려면:
- (void) removereminder:(UILocalNotification*)notification
{
_dataArray = [[NSMutableArray alloc]initWithArray:[[UIApplication sharedApplication]scheduledLocalNotifications]];
NSString * idToDelete = [notification.userInfo objectForKey:@"kRemindMeNotificationDataKey"];
for (int i = 0 ; i<_dataArray.count; i++)
{
UILocalNotification *currentLocalNotification = [_dataArray objectAtIndex:i];
NSString * notificationId = [currentLocalNotification.userInfo objectForKey:@"kRemindMeNotificationDataKey"];
if ([notificationId isEqualToString:idToDelete])
[[UIApplication sharedApplication]cancelLocalNotification:currentLocalNotification];
}
_dataArray = [[NSMutableArray alloc]initWithArray:[[UIApplication sharedApplication]scheduledLocalNotifications]];
[self filterNotficationsArray:_dataArray];
[_remindersTV reloadData];
}
저는 킹 오브 블리스의 대답을 조금 더 확장하고, 이것을 스위프트2처럼 조금 더 작성하고, 불필요한 코드를 제거하고, 몇몇 충돌 보호대를 추가했습니다.
할 때.userInfo
:
notification.userInfo = ["uid": uniqueid]
그런 다음 삭제할 때 다음 작업을 수행할 수 있습니다.
guard
let app: UIApplication = UIApplication.sharedApplication(),
let notifications = app.scheduledLocalNotifications else { return }
for notification in notifications {
if
let userInfo = notification.userInfo,
let uid: String = userInfo["uid"] as? String where uid == uidtodelete {
app.cancelLocalNotification(notification)
print("Deleted local notification for '\(uidtodelete)'")
}
}
이미 배달된 알림 Swift5 삭제
UNUserNotificationCenter.current().getDeliveredNotifications{ (requests) in
for request in requests {
if request.request.identifier == "identifier"{
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["identifier"])
}
}
}
언급URL : https://stackoverflow.com/questions/6340664/delete-a-particular-local-notification
'sourcetip' 카테고리의 다른 글
어떤 것이 null을 나타냅니까?정의되지 않은 문자열 또는 빈 문자열 (0) | 2023.07.27 |
---|---|
Spring 3.0 MVC @ModelAttribute 변수가 URL에 나타나지 않도록 하려면 어떻게 해야 합니까? (0) | 2023.07.27 |
Google 문서와 유사한 라이브 업데이트를 수행하는 방법은 무엇입니까? (0) | 2023.07.27 |
gradle bootRun을 사용하여 명령줄 속성을 추가하는 방법은 무엇입니까? (0) | 2023.07.27 |
범위 '세션'이 현재 스레드에 대해 활성화되지 않았습니다. 불법 상태 예외:스레드 바인딩된 요청을 찾을 수 없습니다. (0) | 2023.07.27 |