0

Silent push notification work properly when app active in foreground

2016-12-26 15:06:17.793051 App[] didReceive in BG!!!
2016-12-26 15:06:17.932569 App[] Connected!
2016-12-26 15:06:17.936581 App[] Subscribed!
2016-12-26 15:06:17.938355 App[] received:Hello World , in:/topic/state

When app runs in background.It will stuck

2016-12-26 15:06:22.674577 App[] applicationWillResignActive
2016-12-26 15:06:23.228441 App[] applicationDidEnterBackground

First silent push arrive,It's stuck in here:

2016-12-26 15:06:30.642825 App[] didReceive in BG!!! //first push code
2016-12-26 15:06:31.842432 App[] Connected!  //first push code
2016-12-26 15:06:31.843643 App[] Subscribed!  //first push code

When second silent push arrive, it shows first push result..and stuck again.....

2016-12-26 15:06:41.713718 App[] received:Hello World , in:/topic/state  //first push result
2016-12-26 15:06:41.740015 App[] didReceive in BG!!!  //second push
2016-12-26 15:06:42.911593 App[] Connected!  //second push
2016-12-26 15:06:42.913403 App[] Subscribed!  //second push

My implement code in Appdelegate

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    NSLog("didReceive in BG!!!" )
    application.delegate = self
    mqttSession = MQTTSession(host: "192.168.159.110", port: 1883, clientID: "swift", cleanSession: true, keepAlive: 5, useSSL: false)
    mqttSession.username = "bucky"
    mqttSession.password = "bucky"
    mqttSession.delegate = self

        mqttSession.connect { (succeeded, error) -> Void in
            if succeeded {
                NSLog("Connected!")

            }
        }
    completionHandler(.newData)
}

MQTT delegate method

func mqttDidReceive(message data: Data, in topic: String, from session: MQTTSession) {
    let stringData = String(data: data, encoding: .utf8)
    NSLog("received:%@ , in:%@", stringData ?? "12345", topic)                        
    }
}
Labuck Wu
  • 3
  • 3

1 Answers1

0

You have to call completionHandler() when you finish attending the notification, but you are calling it immediately. You'd better callint it in mqttDidReceive and in the error delegate method.

Gabriel
  • 3,319
  • 1
  • 16
  • 21
  • Sorry..But I don't know how to add completionHandler in the MQTT delegate method, I will do some survey, thanks anyway~ – Labuck Wu Dec 26 '16 at 09:20
  • Finally I put completionHandler() in DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { completionHandler(.newData) }, and it work properly~ thank you – Labuck Wu Dec 27 '16 at 02:17