在iOS 10中实现“从锁定屏幕回复通知”

时间:2016-09-19 23:56:09

标签: ios

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

感谢。

1 个答案:

答案 0 :(得分:8)

互联网上缺乏结构良好的信息,虽然它是非常好的功能,在严肃的信使应用程序中实现。

您应该从UNNotificationContentExtension开始,以显示收到的推送通知的自定义UI。在互联网上获取任何可用的示例并按您的需要实现它。注意捆绑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: "QuickChat", 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)
}