如何在使用 XMPP 框架检索消息时实现本地通知?

问题描述

我正在 swift 中使用 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)")
            }
        }
    }

    ...
}

不幸的是,它没有按预期工作,每次检索到新消息时都不会显示通知。有没有办法解决这个问题?

解决方法

应用在后台时XMPP被disconnoted,如果你想显示通知,你可以使用APNS或VPNS。apns可以直接显示noti,vpns可以唤醒你的应用,然后你可以发送本地通知.