aciidgh / SwiftMQTT

MQTT Client in pure swift ❤️
MIT License
270 stars 71 forks source link

Crash if MQTTSession stream is created and disposed of quickly #33

Closed paulw11 closed 5 years ago

paulw11 commented 6 years ago

I was getting a crash in SwiftMQTT if there was a short period between the creation and dispose of an MQTTSessionStream - the problem is that the [weak self] has been released before the async block executes on the sessionQueue. The following check addresses the issue:

sessionQueue.async { [weak self] in if self != nil { let currentRunLoop = RunLoop.current inputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode) outputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode) inputStream?.open() outputStream?.open() if ssl { let securityLevel = StreamSocketSecurityLevel.negotiatedSSL.rawValue inputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey) outputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey) } if timeout > 0 { DispatchQueue.global().asyncAfter(deadline: .now() + timeout) { self?.connectTimeout() } }

            currentRunLoop.run()
        }
    }
}
paulw11 commented 6 years ago

Actually this code doesn't fix it :(

adolfo commented 6 years ago

@paulw11 could you write a failing test that reproduces this issue? A PR that fixes the problem is also appreciated if you find the solution.

Jeffkenly88 commented 5 years ago

@adolfo Hi, I'm having the same issue, it happens not regularly, I just had to restart the app multiple times and it happens 1 time out of 10. It crashed with BAD_ACCESS exception on currentRunLoop.run()

Kerry50407 commented 5 years ago

I simply moved the let currentRunLoop = RunLoop.current out of the queue scope, Like this..

let currentRunLoop = RunLoop.current sessionQueue.async { [weak self] in inputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode) ..... currentRunLoop.run() }

The app stop crashing. I guess it happened due to the currentRunLoop is released. (not sure for the root cause)

Hope it helps!

adolfo commented 5 years ago

Resolved in #40