在 iOS 10 中实现"reply to notification from lock screen"



我们有一个消息应用程序,旨在显示通知,当它收到消息时,手机被锁定从远程用户,并让本地用户从锁屏输入文本,并发送消息。我该如何实现呢?UNUserNotificationCenter在iOS 10中是可行的吗?

谢谢。

互联网上缺乏结构良好的信息,尽管这是一个非常好的功能,在严肃的信使应用程序中实现。

您应该从UNNotificationContentExtension开始显示接收到的推送通知的自定义UI。在互联网上选择任何可用的示例,并按照您的意愿实现它。注意bundle ID -它应该是com.yourapp.yourextension。完成后,你将在Xcode中拥有主应用程序和扩展小部件。

在主应用程序中以iOS10的方式设置推送通知注册:

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (granted, error) in
        guard granted else { return }
        let replyAction = UNTextInputNotificationAction(identifier: "ReplyAction", title: "Reply", options: [])
        let openAppAction = UNNotificationAction(identifier: "OpenAppAction", title: "Open app", options: [.foreground])
        let quickReplyCategory = UNNotificationCategory(identifier: "QuickReply", actions: [replyAction, openAppAction], intentIdentifiers: [], options: [])
        UNUserNotificationCenter.current().setNotificationCategories([quickReplyCategory])
        
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            guard settings.authorizationStatus == .authorized else { return }
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

所有的魔法发生在UNTextInputNotificationAction自定义动作,你添加到你的推送通知处理程序。

要完成设置推送通知,请在扩展名 Info.plist: NSExtension -> NSExtensionAttributes -> UNNotificationExtensionCategory: "QuickReply"

中添加此参数

这都是关于设置。要尝试它,使用Pusher工具并以这种方式配置推送通知:

{
    "aps": {
        "alert":"Trigger quick reply",
        "category":"QuickReply"
    }
}

至少你必须在你的小部件中捕获通知。它发生在控件类的func didReceive(_ notification: UNNotification)中:

func didReceive(_ notification: UNNotification) {
    let message = notification.request.content.body
    let userInfo = notification.request.content.userInfo
    // populate data from received Push Notification in your widget UI...
}

如果用户响应收到的推送通知,您的小部件将触发以下回调:

func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
    if response.actionIdentifier == "ReplyAction" {
        if let textResponse = response as? UNTextInputNotificationResponse {
            // Do whatever you like with user text response...
            completion(.doNotDismiss)
            return
        }
    }
    completion(.dismiss)
}

最新更新