2017-06-02 13 views
2

UNUserNotificationCenterから新しいローカル通知を使用して削除されるまで待ちます。 私はいくつかの識別子との通知を削除しよう:UNUserNotificationCenterのローカル通知がremovePendingNotificationRequests ios 10 swift 3

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers) 

とdocumentionから:

この方法は、二次スレッドで保留通知要求を削除し、非同期に実行されます。

補完ハンドラが存在しません。どうすればその本当に削除されるのを知ることができますか?先に進む前に、私はこの識別子がもう存在しないことを確認する必要があります。

私は

notificationCenter.getPendingNotificationRequests { (requests) in 
     for request in requests { 
     } 
} 

私は次のコードを使用することができます知っている。しかし、私は右削除した後に、このコードを実行する場合 - 彼らはまだそこにあります。しかし、しばらくするとコードの後で、彼らはなくなってしまいます。特にその重要なあなたが金持ちに64件の通知

の上限をおよそ再度新しいものを追加する前に しばらくした後、私は次のいずれかの方法を発見したような

答えて

0

[OK]をルックス - そのDispatchGroup そのuserInteractive品質で非同期の方法でも行わ:

let dq = DispatchQueue.global(qos: .userInteractive) 
dq.async { 
    let group = DispatchGroup() 
    group.enter() 
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: arr) 
group.leave() 

    group.notify(queue: DispatchQueue.main) {() in 
     UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in 
      for request in requests { 
       print("||=> Existing identifier is \(request.identifier)") 
      } 
     } 
    }   
} 

、削除通知がgetPendingNotificationRequests

+0

removePendingNotificationRequestsはまだ別のスレッドで実行されるため、グループはすぐに終了するため、機能しないと思います。 group.leaveがthreadで呼び出され、removePendingNotificationRequestsが –

0

に存在していないあなたはあなたの答えに投稿されたように、すべてのその複雑なロジックを行う必要はありませんので。 removeAllPendingNotificationRequestsに電話して、getPendingNotificationRequestsの方法で処理が完了するまで待つことができます。以下のコードを実行すると、何が起こるかを見ることができます。直ちにが印刷され、1..63から数字が0になることがわかります。

let notificationCenter = UNUserNotificationCenter.current() 

    for i in 1 ... 63 { 
     let components: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second] 

     let date = Calendar.current.date(byAdding: .hour, value: 1, to: Date())! 

     let dateComponents = Calendar.current.dateComponents(components, from: date) 

     let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) 

     let content = UNMutableNotificationContent() 

     content.title = "Title" 
     content.body = "Body" 
     content.sound = UNNotificationSound.default() 

     let request = UNNotificationRequest(identifier: "id" + String(i), 
       content: content, trigger: trigger) 

     notificationCenter.add(request) { 
      (error) in 

      print(i) 
     } 
    } 

    notificationCenter.removeAllPendingNotificationRequests() 

    print("after remove") 

    notificationCenter.getPendingNotificationRequests() { 
     requests in 
     print(requests.count) 
    } 

すべてのタスクがキューに入れられ、1つずつ実行されるため、その理由は同じです。したがって、最初に63個の通知を入れてから削除し、最後にそれを数えます。これらのタスクは厳密に1つずつ進みます。

関連する問題