[ios] add TrackRecording state observation

To bind state with the button on the main screen

Signed-off-by: Kiryl Kaveryn <kirylkaveryn@gmail.com>
This commit is contained in:
Kiryl Kaveryn 2024-10-15 20:50:50 +04:00 committed by Roman Tsisyk
parent 592b5bf595
commit 4a33a609d8

View file

@ -13,7 +13,7 @@ enum TrackRecordingError: Error {
case locationIsProhibited
}
typealias TrackRecordingStateHandler = (TrackRecordingState) -> Void
typealias TrackRecordingStateHandler = (Bool) -> Void
@objcMembers
final class TrackRecordingManager: NSObject {
@ -33,7 +33,12 @@ final class TrackRecordingManager: NSObject {
static let shared: TrackRecordingManager = TrackRecordingManager(trackRecorder: FrameworkHelper.self)
private let trackRecorder: TrackRecorder.Type
private(set) var recordingState: TrackRecordingState = .inactive
private var observations: [Observation] = []
private(set) var recordingState: TrackRecordingState = .inactive {
didSet {
notifyObservers()
}
}
private init(trackRecorder: TrackRecorder.Type) {
self.trackRecorder = trackRecorder
@ -41,6 +46,11 @@ final class TrackRecordingManager: NSObject {
self.recordingState = getCurrentRecordingState()
}
@objc
func isActive() -> Bool {
recordingState == .active
}
func processAction(_ action: TrackRecordingAction, completion: (CompletionHandler)? = nil) {
switch action {
case .start:
@ -50,10 +60,26 @@ final class TrackRecordingManager: NSObject {
}
}
@objc
func addObserver(_ observer: AnyObject, recordingIsActiveDidChangeHandler: @escaping TrackRecordingStateHandler) {
let observation = Observation(observer: observer, recordingStateDidChangeHandler: recordingIsActiveDidChangeHandler)
observations.append(observation)
recordingIsActiveDidChangeHandler(recordingState == .active)
}
@objc
func removeObserver(_ observer: AnyObject) {
observations.removeAll { $0.observer === observer }
}
private func notifyObservers() {
observations = observations.filter { $0.observer != nil }
observations.forEach { $0.recordingStateDidChangeHandler?(recordingState == .active) }
}
private func handleError(_ error: TrackRecordingError, completion: (CompletionHandler)? = nil) {
switch error {
case .locationIsProhibited:
completion?()
// Show alert to enable location
LocationManager.checkLocationStatus()
}
@ -75,7 +101,7 @@ final class TrackRecordingManager: NSObject {
recordingState = .active
completion?()
case .active:
break
completion?()
case .error(let trackRecordingError):
handleError(trackRecordingError, completion: completion)
}