在iOS 10中实现“锁屏界面回复通知”的功能

9
我们有一个消息应用程序,旨在在手机被远程用户锁定时接收消息并显示通知,让本地用户可以从锁屏界面输入文本并发送消息。如何实现这一功能?iOS 10中的UNUserNotificationCenter是否是最佳选择?
谢谢。
1个回答

19

虽然现有的严肃的即时通讯应用程序已经实现了非常好的功能,但是在互联网上缺乏良好结构化的信息。

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

在主应用程序中使用iOS 10方式设置推送通知注册:

    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)
}

我按照您的步骤进行了操作,一切都很顺利。但是我卡在了“ReplyAction”这一步。我想在“ReplyAction”中调用API。通知内容扩展中是否可以调用API?如果可以,您能否给我指点如何实现呢? - bittu
@bittu 当然,您可以在那里运行任何代码。当调用API请求时,意味着您有一些完成处理程序,在其中从API获取响应。在该处理程序中,您调用 yourNotificationContentExtension.completionHandler(.dismiss)。另一个问题是如何将API凭据从主应用程序传递到扩展程序 - 您应该使用共享的“用户默认值”来实现。 - brigadir
@bittu 我也在尝试在操作按钮上调用API,但是在alamofire中我遇到了网络丢失错误。 - jayant rawat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接