ios - 在 iOS 通知内容扩展中关闭键盘

标签 ios swift apple-push-notifications

我通过通知内容扩展目标在我的 iOS 11 通知窗口中显示自定义操作按钮。其中之一是“评论”按钮。如果我按下它,键盘会正确显示,但我无法弄清楚如何让键盘消失并返回到通知上的其他按钮。我看不到任何调用 resignFirstResponder 的东西。我只是遗漏了一些非常明显的东西吗?

最佳答案

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

没有内容扩展 第一个甚至不需要通知内容扩展! 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 session Advanced Notifications描述了相同的用例并详细说明了进一步定制的方法。

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

例如,这个:

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 上,对通知本身的任何点击 - 例如在您的文本字段上 - 都可能导致它被关闭!由于这个和许多其他原因,走这条路可能是不可取的。

关于ios - 在 iOS 通知内容扩展中关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51779507/

相关文章:

ios - 从外部调用函数后,Collectionviewcontroller 上的 Swift 变量重置

iphone - 使用 UINavigationController 还是 ContentController?

ios - 导出通用分发框架

swift - 我该如何解决此错误 :unrecognised selector sent to instance (LongPress onUIImageView)

c# - Xamarin.Forms - iOS RegisteredForRemoteNotifications 没有被调用

ios - Swift2 中 ALCameraViewController 的语法错误

arrays - 正确从数组中删除数据

swift - 如何检查用户是否需要使用 Firebase 身份验证重新进行身份验证

ios - 缺少 "aps-environment"权利。注册失败

iphone - 如果我删除后下载相同的应用程序,ANPS 的设备 token 是否会更改?