2016-08-12 4 views
6

이 질문은 내가 로컬 통지는 사용자 후 매 30 분마다 1 시간에서 시작, 응용 프로그램에서 특정 행동을했던 일정 응용 프로그램이 아이폰 OS (10)iOS 10에 UNUserNotificationCenterDelegate와 함께 새 알림이 도착하면 이전에 배달 된 알림을 어떻게 제거 할 수 있습니까?

의 새로운 UserNotifications 프레임 워크에 관한 것입니다.

사용자의 잠금 화면이나 알림 센터가 어수선하게 흩어지는 일이 없도록 한 번에 하나의 알림 만 표시되도록하려면 가장 최근의 관련 정보가있는 알림이 하나뿐입니다. 이를 달성하기위한 나의 계획은 새로운 알림이 제시 될 때마다 모든 전달 된 알림을 삭제하는 것입니다.

새로운 willPresent 방법이 UNUserNotificationCenterDelegate 일 수 있어야하지만 예상대로 작동하지 않습니다.

func updateNotifications() { 

    for hour in 1...23 { 
     scheduleNotification(withOffsetInHours: Double(hour)) 
     scheduleNotification(withOffsetInHours: Double(hour) + 0.5) 
    } 
} 
: 여기

내가 응용 프로그램의 이벤트 후 1시간에서 시작, 이벤트 후 23.5 시간에서 마지막까지 알림을 매 30 시간 예약, 모든 알림을 설정하기 위해 호출하는 기능입니다

willPresent 방법은 U를 설정 내 UNUserNotificationCenterDelegate에서
func scheduleNotification(withOffsetInHours: Double) { 

    // set up a Date for when the notification should fire 
    let offsetInSeconds = 60 * 60 * withOffsetInHours 
    let offsetFireDate = mostRecentEventDate.addingTimeInterval(offsetInSeconds) 

    // set up the content of the notification 
    let content = UNMutableNotificationContent() 
    content.categoryIdentifier = "reminder" 
    content.sound = UNNotificationSound.default() 
    content.title = "Attention!" 
    content.body = "It has been \(withOffsetInHours) hours since the most recent event." 

    // set up the trigger 
    let triggerDateComponents = Calendar.current.components([.year, .month, .day, .hour, .minute, .second], from: offsetFireDate) 
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDateComponents, repeats: false) 

    // set up the request 
    let identifier = "reminder\(withOffsetInHours)" 
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) 

    // add the request for this notification 
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in 

     if error != nil { 

      print(error) 
     } 
    }) 
} 

내가 한 :

이 는 Date 다른 설정입니다 실제로 일정 알림이 mostRecentEventDate에 따라 기능입니다 이 같은 P :

func userNotificationCenter(_: UNUserNotificationCenter, willPresent: UNNotification, withCompletionHandler: (UNNotificationPresentationOptions) -> Void) { 

    print("will present...") 

    UNUserNotificationCenter.current().removeAllDeliveredNotifications() 

    withCompletionHandler([.alert,.sound]) 
} 

나는 "... 선물 할 것이다"가 인쇄 때문에 willPresent 함수가 호출되는 알고 있지만 알림 센터에서 기존 알림 삭제되지 않습니다. 왜 이것이 작동하지 않는지 아는 사람이 있습니까? 또는 내가 원하는 방식대로 작동하도록하는 방법이 있다면?


편집 : 나는 같은 일을 달성하기 위해 다른 접근 방식 함께했다, 그러나 또한 작동하지 않습니다. 여기

내 생각은 (트리거없이) 즉시 도착하는 또 다른 알림을 예약하는 동안 수신 예약 알림을 침묵 willPresent를 사용하는 것이 었습니다. 모든 알림은 그 식별자가 기존의 통지가 항상 교체해야합니다 있도록 새 UserNotifications 프레임 워크에 대해 this 2016 WWDC talk 20:00 주위의 예에서와 같이, 즉시 도착 동일한 식별자를 가질 예정된다. 여기 내 업데이트 willPresent 방법입니다 :

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent: UNNotification, withCompletionHandler: (UNNotificationPresentationOptions) -> Void) { 

    let identifier = willPresent.request.identifier 

    if identifier != "reminder" { 

     let offsetInHoursString = identifier.replacingOccurrences(of: "reminder", with: "") 

     let content = UNMutableNotificationContent() 
     content.categoryIdentifier = "reminder" 
     content.sound = UNNotificationSound.default() 
     content.title = "Attention!" 
     content.body = "It has been \(offsetInHoursString) hours since the most recent event." 

     let identifier = "hydrationReminder" 

     let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil) 

     center.add(request, withCompletionHandler: { (error) in 

      if error != nil { 

       print(error) 
      } 
     }) 

     withCompletionHandler([]) 

    } else { 

     withCompletionHandler([.alert,.sound]) 
    } 
} 

편집 : 내가 마지막으로, 앱이 포 그라운드에있는 경우가 바로 this page의 맨 위에 말한대로 willPresent만, 호출 것을 깨달았다 그래서 이러한 접근 방식 중 어느 것도 실제로 작동하지 않아야합니다. 나는 알림이 수신 될 때마다 willPresent이 호출 될 것이라고 생각했다. 위로 드로잉 보드이 "단지 최신의, 가장 관련 통지"생각에 ...

답변

0
+1

알림을 지우는 데 올바른 기능이지만 문제가 발생합니다. 여기서 문제는 원격이 아닌 알림이 전달되고 앱이 포 그라운드에 있지 않을 때 호출되는 메서드가 없으므로 이미 전달 된 알림을 지우려면 알림이 전달 될 때 해당 앱을 호출 할 수 없습니다. – gohnjanotis

+0

아직 솔루션을 찾으십니까? 같은 문제. – Justin

+0

@gohnjanot이 도움이 될지 확실하지 않지만 내 답변 [여기] (https://stackoverflow.com/questions/44363767/assure-delivery-of-uilocalnotification-on-currect-time-ios/44364338#44364338)을 참조하십시오.) – Honey

1

당신은 당신이 "업데이트 알림"이라고합니다 기능을 달성 할 생각이 demo.

확인할 수 있습니다 사용할 수 있습니다.

iOS 10 알림을 업데이트 할 수 있습니다. 방금 보내신 알림 - 알림은 동일하게 유지하십시오. 식별자.

  1. 첫 번째 알림 :

    의 데모를 보자

NSURL * imageUrl = [[NSBundle mainBundle] URLForResource:@"dog" withExtension:@"png"]; 
 
    UNNotificationAttachment *imgAtt = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:imageUrl options:nil error:&error]; 
 
    
 
    NSURL * mp4Url = [[NSBundle mainBundle] URLForResource:@"media" withExtension:@"mp4"]; 
 
    UNNotificationAttachment *mediaAtt = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:mp4Url options:nil error:&error]; 
 
    
 
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init]; 
 
    //在通知中心显示的总是第一个多媒体资源 
 
    content.attachments = @[imgAtt,mediaAtt]; 
 
    content.badge = @1; 
 
    content.title = @"Wake Up"; 
 
    content.subtitle = @"First time"; 
 
    content.body = @"next time。。。 "; 
 
    content.categoryIdentifier = @"wakeup"; 
 
    content.launchImageName = @"dog"; 
 
    content.sound = [UNNotificationSound defaultSound]; 
 
// content.threadIdentifier = @""; 
 
    content.userInfo = @{@"first":@"5:00 am",@"second":@"6:00"}; 
 
    
 
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.0 repeats:NO]; 
 
    
 
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"com.junglesong.pushtestdemo.wakeup" content:content trigger:trigger]; 
 
    
 
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { 
 
     NSLog(@"wake up message has been deliverd!"); 
 
    }];

  • 갱신 최초 통보
      :
    을 012 시스템이 그냥 단지 sencond 처음 one.In 아이폰 OS (10) 대체 테이크 원 same.So로 취급 notification.But 3,516,

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init]; 
     
        content.badge = @1; 
     
        content.title = @"Update!dear,wake up"; 
     
        content.subtitle = @"Update! dear,please"; 
     
        content.body = @"Update!shall we have breakfast?"; 
     
        content.categoryIdentifier = @"wakeup"; 
     
        content.launchImageName = @"dog"; 
     
        content.sound = [UNNotificationSound defaultSound]; 
     
        // content.threadIdentifier = @""; 
     
        content.userInfo = @{@"first":@"5:00 am",@"second":@"6:00"}; 
     
        
     
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.0 repeats:NO]; 
     
        
     
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"com.junglesong.pushtestdemo.wakeup" content:content trigger:trigger]; 
     
        
     
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { 
     
         NSLog(@"wake up message has been updated!"); 
     
        }];

    이제 두를 추가,이 업데이 트를 호출.

    "식별자"속성은 알림을 구분할 수있는 UNNotificationRequest의 ID입니다.

  • +1

    이것이 해결책 일 수있는 것처럼 보일지 모르지만,이 방법으로 동일한 식별자를 사용하려고하면 하나의 통지만으로 끝납니다. 마지막 업데이트에 대한 정보 만 제공되며 새 알림이 전달 될 때마다 업데이트 된 알림을 표시하도록 예약 된 여러 알림 업데이트가 아닌 한 번 표시됩니다. – gohnjanotis