How to keep GCKCastSession alive when app goes to background

China☆狼群 提交于 2019-11-30 16:42:41

In the latest Google Cast SDK, you can set it in the options like so:

let criteria = GCKDiscoveryCriteria(applicationID: kGCKDefaultMediaReceiverApplicationID)
var options = GCKCastOptions(discoveryCriteria: criteria)
options.suspendSessionsWhenBackgrounded = false
GCKCastContext.setSharedInstanceWith(options)

However, regardless of that, the session dies from a lost network connection. The trick becomes playing an "empty" audio file from the device, which keeps it alive. Stupid to think that this must be the industry standard.

As Google Cast SDK calls GCKSessionManager.suspendSessionWithReason when the app goes to background, one solution is to replace this method with a different implementation that checks if the reason is .AppBackgrounded and then actually ignores the call.

Then SDK doesn't kill the the session immediately when app goes to background but it will still suspend the session at a later point. The session can however be restarted from background mode – it however takes significant time and that delay is negatively perceived from the user perspective. Furthermore the session regularly suspends again after a few seconds of not "talking to it".

Any better solution is still very much appreciated.

extension GCKSessionManager {
    static func ignoreAppBackgroundModeChange() {
        let oldMethod = class_getInstanceMethod(GCKSessionManager.self, #selector(GCKSessionManager.suspendSessionWithReason))
        let newMethod = class_getInstanceMethod(GCKSessionManager.self, #selector(GCKSessionManager.suspendSessionWithReasonIgnoringAppBackgrounded))
        method_exchangeImplementations(oldMethod, newMethod)
    }

    func suspendSessionWithReasonIgnoringAppBackgrounded(reason: GCKConnectionSuspendReason) -> Bool {
        guard reason != .AppBackgrounded else { return false }
        return suspendSessionWithReason(reason)
    }
}

All we need to do now is to call GCKSessionManager.ignoreAppBackgroundModeChange().

Edit:

As of latest Google Cast SDK, it has a new option to keep sessions alive in background.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!