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

lgc*_*stc 6 ios

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

谢谢.

bri*_*dir 11

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

您应该首先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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

所有魔法都发生在UNTextInputNotificationAction您添加到推送通知处理程序的自定义操作中.

要完成设置推送通知,请在您的扩展程序中 添加此参数Info.plist:NSExtension -> NSExtensionAttributes -> UNNotificationExtensionCategory: "QuickReply"

这一切都与设置有关.要尝试它,请使用Pusher工具并以这种方式配置推送通知:

{
    "aps": {
        "alert":"Trigger quick reply",
        "category":"QuickReply"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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...
}
Run Code Online (Sandbox Code Playgroud)

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

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)
}
Run Code Online (Sandbox Code Playgroud)