2017-06-27 37 views
2

我正在爲我的應用使用UserNotifications實施一種警報通知。當3D觸摸此通知時,我希望它顯示一些「警報信息」,並選擇「暫停」警報,這將在5分鐘內有效地重複通知。 這一切都工作正常,但通知不會被解僱,當我點擊貪睡按鈕。如何通過自定義操作解除3D觸摸的通知?

我使用的是NotificationContentExtension來修改內容,並帶有categoryIdentifier "ReminderNotificationExtensionCategory"。然後,我創建了我的代碼類是這樣的:

let snooze = UNNotificationAction(identifier: "snoozeActionIdentifier", title: NSLocalizedString("SNOOZE", comment: ""), options: .foreground) 
let reminderCategory = UNNotificationCategory(identifier: "ReminderNotificationExtensionCategory", actions: [snooze], intentIdentifiers: [], options: .customDismissAction) 

UNUserNotificationCenter.current().setNotificationCategories([reminderCategory])//Not sure if I should set this every time or just once.. 

然後創建我的通知對象

let content = UNMutableNotificationContent()   
content.categoryIdentifier = "ReminderNotificationExtensionCategory" 
content.title = "test" 
content.body = "test" 
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false) //Fire in 3 seconds 
let request = UNNotificationRequest(identifier: "someIdentifier, content: content, trigger: trigger) 
UNUserNotificationCenter.current().add(request) { (error:Error?) in /**/} 

現在,我的通知將在3秒內發送。 我鎖定我的屏幕並接收它,它看起來不錯。當我3D觸摸它時,我的擴展程序啓動,並且我已經設置了一個UIView的潛行峯,以及通知下方的「貪睡」按鈕,如圖所示:(內容已刪除)Notification

當我點擊「打盹」 - 按鈕,一個UNNotificationContentExtension委託-方法將被調用,特別是func didReceive(_ response: completion:) 完成只接受的UNNotificationContentExtensionResponseOption的值,這將是要麼.dismiss.doNotDismiss,或者.dismissAndForwardAction。 只是用於測試,我已經這樣做了:

func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) { 
    print("This is happening. ActionIdentifier: ", response.actionIdentifier) 
    completion(.dismiss) 
} 

當我調試通知擴展,打印確確實實發生了。它打印出"This is happening. ActionIdentifier: snoozeActionIdentifier"。但是,通知並未被解僱。 如果我從.dismiss更改爲.doNotDismiss,則沒有任何更改。它仍然不排除。如果我更改爲.dismissAndForwardAction,它會解散並打開我的應用程序。

我找不到任何人有這個問題。我想.dismiss解僱我的通知。爲什麼不是?難道我做錯了什麼?

編輯 我現在看到這兩個場景發生:

  1. 我的3D觸摸在鎖定屏幕上我的通知,然後點外面,我的通知「崩潰」,並定期通知在我3D觸摸它之前是可見的。

  2. 我通過鎖屏觸摸我的通知,點擊「延後」(沒有任何反應),然後點擊通知外部,常規通知消失。

因此,完成回調實際上並不會解除正常通知,而是解除了擴展。爲什麼?我怎樣才能解僱延期?這是我必須調用的手動方法嗎?

+0

我對你的問題感到困惑。你的意思是當你按下貪睡時,它會打開應用程序,但是貪睡通知仍然在你的屏幕上? – Honey

+0

@Honey如果我用'.dismissAndForwardAction'調用完成處理程序,它會打開我的應用程序。如果我用'.dismiss'調用完成處理程序,則完全沒有任何事情發生(例如,它既沒有關閉也沒有打開應用程序)。原來問題出在我初始化notificationAction的時候。顯然,'UNNotificationActionOptions'描述了按鈕的作用,'UNNotificationContentExtensionResponseOption'描述了操作發生後通知應該做什麼。事實證明,通知的'.dismiss'與按鈕的'.foreground'不匹配。 – Sti

回答

2

我現在明白了我的愚蠢錯誤..

正如你可以在上面我的代碼看,我在我的類實例化的操作按鈕這樣:

let snooze = UNNotificationAction(identifier: "snoozeActionIdentifier", title: NSLocalizedString("SNOOZE", comment: ""), options: .foreground) 

在最後,我指定的選項.foreground。這應該只是一個空的數組[]爲我的目的。

我,雖然我必須指定一個選項,並輸入類型爲的UNNotificationActionOptions,其中只有選項.authenticationRequired(「不,我不想說」).destructive(「不,我不想要一個紅色的按鈕「)和.foreground(」好吧,如果我必須選擇一個如果這些..「)。原來,只是指定一個空的數組[]做了伎倆。