【发布时间】:2021-08-24 05:23:50
【问题描述】:
我正在快速使用 XMPP 框架制作一个聊天应用程序。我想要做的是每当检索到新消息时,应用程序都会显示本地通知。我尝试使用NotificationCenter 来实现这一点,但显然它没有按预期工作。这是我的实现代码:
extension XmppProvider: XMPPStreamDelegate {
...
func xmppStream(_ sender: XMPPStream, didReceive message: XMPPMessage) {
print(message)
// ... code to create a message dictionary goes here ...
// Everytime a message is retrieved, it uses NotificationCenter to show a notification when the app is in background
NotificationCenter.default.post(name: NSNotification.Name("showLocalNotification"), object: messageDictonary)
}
}
我在AppDelegate.swift 中添加了一个通知观察者,如下所示:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
NotificationCenter.default.addObserver(self, selector: #selector(showLocalChatNotification(_:)), name: NSNotification.Name("showLocalNotification"), object: nil)
}
@objc private func showLocalChatNotification(_ notification: Notification) {
let object = notification.object as! Dictionary<String, String>
let name = object["name"]
let message = object["message"]
let content = UNMutableNotificationContent()
content.title = name!
content.body = message!
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "localChatNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Local notification error \(error.localizedDescription)")
}
}
}
...
}
不幸的是,它没有按预期工作,每次检索到新消息时都不会显示通知。有没有办法解决这个问题?
【问题讨论】:
标签: ios swift xmpp xmppframework