diff --git a/MVMCoreUI/Atomic/Atoms/Views/Video.swift b/MVMCoreUI/Atomic/Atoms/Views/Video.swift index f869ab06..92ff3ecf 100644 --- a/MVMCoreUI/Atomic/Atoms/Views/Video.swift +++ b/MVMCoreUI/Atomic/Atoms/Views/Video.swift @@ -51,6 +51,7 @@ open class Video: View { // Handle pause behavior model.addVisibleBehavior(for: self, delegateObject: delegateObject) model.addScrollBehavior(for: self, delegateObject: delegateObject) + model.addActiveListener(for: self, delegateObject: delegateObject) } /// Listens and responds to video loading state changes. diff --git a/MVMCoreUI/Atomic/Atoms/Views/VideoModel.swift b/MVMCoreUI/Atomic/Atoms/Views/VideoModel.swift index 8bc3d827..9b1d4f71 100644 --- a/MVMCoreUI/Atomic/Atoms/Views/VideoModel.swift +++ b/MVMCoreUI/Atomic/Atoms/Views/VideoModel.swift @@ -24,6 +24,8 @@ open class VideoModel: MoleculeModelProtocol { private weak var visibleBehavior: PageVisibilityClosureBehavior? private weak var scrollBehavior: PageScrolledClosureBehavior? + private var activeListener: Any? + private var resignActiveListener: Any? private enum CodingKeys: String, CodingKey { case moleculeName @@ -113,9 +115,8 @@ open class VideoModel: MoleculeModelProtocol { let onScroll = { [weak self] (scrollView: UIScrollView) in // If visible to not visible, pause video. // If not visible to visible, unpause if needed, add visible behavior - guard let self = self, - let containingView = (delegateObject?.moleculeDelegate as? UIViewController)?.view else { return } - if !MVMCoreUIUtility.isView(view, visibleIn: containingView) { + guard let self = self else { return } + if !MVMCoreUIUtility.isView(view, visibleIn: scrollView) { self.haltVideo() } else { self.unhaltVideo() @@ -132,4 +133,33 @@ open class VideoModel: MoleculeModelProtocol { delegate.add(behavior: scrollBehavior) self.scrollBehavior = scrollBehavior } + + open func addActiveListener(for view: Video, delegateObject: MVMCoreUIDelegateObject?) { + removeActiveListener() + + guard let containingView = (delegateObject?.moleculeDelegate as? UIViewController)?.view else { return } + resignActiveListener = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] (notification) in + self?.haltVideo() + } + activeListener = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] (notification) in + if MVMCoreUIUtility.isView(view, visibleIn: containingView) { + self?.unhaltVideo() + } + } + } + + private func removeActiveListener() { + if let observer = activeListener { + NotificationCenter.default.removeObserver(observer) + activeListener = nil + } + if let observer = resignActiveListener { + NotificationCenter.default.removeObserver(observer) + resignActiveListener = nil + } + } + + deinit { + removeActiveListener() + } }