novastone-media / MQTT-Client-Framework

iOS, macOS, tvOS native ObjectiveC MQTT Client Framework
Other
1.84k stars 466 forks source link

How do I adapt this code to maintain the connection in background? #469

Closed nathanmrtns closed 6 years ago

nathanmrtns commented 6 years ago

Hi, every time the app goes to background the connection closes. I've seen some codes here that is possible to maintain the connection but I don't know how to adapt. Any help?

        let session = MQTTSession()
        let transport: MQTTWebsocketTransport = MQTTWebsocketTransport()
        transport.host = "host address"
        transport.path = "/mqtt"
        transport.port = port
        transport.tls = true
        session.transport = transport
        session.userName = "username"
        session.password = "pass"
        session.protocolLevel = .version311
        session.clientId = String(ProcessInfo().processIdentifier)
        session.connect()
jcavar commented 6 years ago

Just don't disconnect and start background task:

https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtask

This will work for short running tasks, for long running your app needs to be in category of apps that are allowed to exectute long running background task, e.g voip

nathanmrtns commented 6 years ago

@jcavar What about the MQTTSessionManager with the connectInForeground flag?

jcavar commented 6 years ago

That is I think opposite of what you want. MQTTSessionManager can handle reconnection when coming from background, but you don't want to disconnect when you go to background?

nathanmrtns commented 6 years ago

@jcavar I see. Yeah, I want to keep the connection if the app goes to background.

nathanmrtns commented 6 years ago

The connection was closing when I blocked the device. I just made an observer that is notified everytime the application goes foreground and the session is not connected. This resolved my problem, but any other suggestion is welcome :)