2017-01-04 49 views
4

我遇到一個奇怪的錯誤與iOS 10.2與UNTimeIntervalNotificationTriggerUNUserNotificationCenterDelegate。基本上,我創建的通知會立即被代表接收,然後再次在正確的內部接收。只有在觸發器上的repeats屬性設置爲true時纔會發生這種情況。iOS 10.2 UNUserNotificationCenterDelegate/UNTimeIntervalNotificationTrigger Bug?

有其他人看過這個問題嗎?現在我想我需要檢查委託中的觸發日期,並與存儲的註冊日期進行比較 - 但如果可能的話,我想避免這種情況。

示例代碼來創建通知

let content = UNMutableNotificationContent() 
content.body = "My notification message" 
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true) 
let request = UNNotificationRequest(identifier: "MY_IDENTIFIER", content: content, trigger: trigger) 

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 

UNUserNotificationCenterDelegate是,如果我改變觸發重複錯誤後。新增

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
     // Code called here instantly when trigger repeats = true 
     // Code called again at proper interval as well (60 seconds) 
} 

直接燃燒,這種情況不會發生

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false) 
+0

Docs說:「如果重複爲true,那麼timeInterval參數中的值必須是60秒或更長。」讓我想知道,選擇一個更大的時間間隔並且看看會發生什麼情況會更好,因爲你是對的,就像那樣。 – matt

+0

它實際上設置了多天,我只是將其更改爲60代碼示例。 –

回答

0

我還沒有找到根本問題,或者看到/聽到過任何其他人的問題。同時這是我的修復(儘管我希望它能正常工作)。

我創建了一個字典來存儲通知被觸發的時間。我使用的通知標識符作爲關鍵:

scheduledTimes[identifier] = CACurrentMediaTime() 
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 

然後在委託時,我可以把它比作當前的時間,看看我是否應該忽略它或不:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    let identifier = notification.request.identifier 

    // Required for 10.2? 
    // Adding a notification request to the notification center immediately fires this delegate when the trigger is set to repeat 
    if let scheduledTime = scheduledTimes[identifier] { 
     if CACurrentMediaTime() - scheduledTime < 1.0 { 
      completionHandler([]) 
      return 
     } 
    } 

    // Parse the notification into an internal notification and show it 

    completionHandler([]) 
} 

的時間之間加入代表電話非常短,平均爲0.04。