iosswiftxmppxmppframework

How to implement local notification when message is retrieved using XMPP Framework?


I'm making a chat app using XMPP Framework in swift. What I want to do is whenever a new message is retrieved, the app shows a local notification. I tried to achieve this using NotificationCenter, but apparently it doesn't work as expected. Here's my implementation code:

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

And I add an notification observer in my AppDelegate.swift like this:

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

    ...
}

Unfortunately it doesn't work as expected, the notification does not show everytime a new message is retrieved. Is there anyway to solve this?


Solution

  • The XMPP is disconnoted when the app on background, If you want to show a notification,You can use APNS or VPNS.The apns can show noti directly,The vpns can wake up you app,Then you can send a local notification.