【问题标题】:How to implement local notification when message is retrieved using XMPP Framework?使用 XMPP 框架检索消息时如何实现本地通知?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2016-12-09
      • 2011-12-09
      • 1970-01-01
      • 2014-01-18
      相关资源
      最近更新 更多