我们有一个消息应用程序,旨在在手机被远程用户锁定时接收消息并显示通知,让本地用户可以从锁屏界面输入文本并发送消息。如何实现这一功能?iOS 10中的UNUserNotificationCenter是否是最佳选择?
谢谢。
谢谢。
虽然现有的严肃的即时通讯应用程序已经实现了非常好的功能,但是在互联网上缺乏良好结构化的信息。
你可以从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)
}
yourNotificationContentExtension.completionHandler(.dismiss)
。另一个问题是如何将API凭据从主应用程序传递到扩展程序 - 您应该使用共享的“用户默认值”来实现。 - brigadir