关闭iOS Notification Content Extension中的键盘

时间:2018-08-10 05:25:24

标签: ios swift apple-push-notifications

我正在通过Notification Content Extension目标在iOS 11通知窗口中显示自定义操作按钮。其中之一是“评论”按钮。如果按此键,键盘会正确显示,但是我不知道如何使键盘消失并返回到通知上的其他按钮。我几乎看不到要打{{1​​}}的任何事情。我只是想念一些确实很明显的东西吗?

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点。

没有内容扩展程序 第一个甚至不需要通知内容扩展! UNTextInputNotificationAction为您完成所有工作。初始化动作时,可以为触发动作时将显示的文本字段指定参数。该操作会在注册过程中附加到您的通知类别中(即在willFinishLaunchingWithOptions中):

userNotificationCenter.getNotificationCategories { (categories) in
    var categories: Set<UNNotificationCategory> = categories
    let inputAction: UNTextInputNotificationAction = UNTextInputNotificationAction(identifier: "org.quellish.textInput", title: "Comment", options: [], textInputButtonTitle: "Done", textInputPlaceholder: "This is awesome!")
    let category: UNNotificationCategory = UNNotificationCategory(identifier: notificationCategory, actions: [inputAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "Placeholder", options: [])

    categories.insert(category)
    userNotificationCenter.setNotificationCategories(categories)
}

这将产生如下体验:

UNTextInputNotificationAction

请注意,默认情况下,“完成”按钮会关闭键盘和通知。

通过一个以上的动作,您会得到:

Multiple actions

没有返回到通知中显示的操作按钮的通知,通知无法做到这一点。要再次查看这些操作选择,则需要显示另一个通知。

带有内容扩展程序 首先,以上部分还适用于内容扩展。当用户完成输入文本并单击“ textInputButton”时,将调用内容扩展的didReceive(_:completionHandler:)方法。这是使用输入或关闭扩展名的机会。 WWDC 2016会议Advanced Notifications描述了相同的用例,并详细说明了可以进一步自定义的方式。

这可能无法满足您的需求。您可能需要具有自定义的文本输入用户界面等。在这种情况下,由您的扩展程序来处理显示和隐藏键盘。当接收到通知时,处理文本输入的响应者(例如UITextField)应成为第一响应者。这样做会显示键盘。辞职第一响应者将隐藏它。这可以在UITextField委托方法中完成。

例如,此:

override var canBecomeFirstResponder: Bool {
    get {
        return true
    }
}

func didReceive(_ notification: UNNotification) {
    self.label?.text = notification.request.content.body
    self.textField?.delegate = self
    self.becomeFirstResponder()
    self.textField?.becomeFirstResponder()
    return
}


// UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.textField?.resignFirstResponder()
    self.resignFirstResponder()
    return true
}

产生这样的结果:

content extension

请记住,在iOS 10和11上,对通知本身的任何轻按(例如在您的文本字段上)都可能导致其被关闭!由于这个原因和其他许多原因,可能不希望采用这种方法。

相关问题