Я работаю над реализацией потоковой реализации с SwiftUI.
Я хочу отслеживать местоположение пользователя и всякий раз, когда происходит новое обновление местоположения. Поэтому я использую промежуточное программное обеспечение. Промежуточное программное обеспечение авторизации и ведения журнала Firebase работает, но не работает отслеживание местоположения. Поскольку newLocation равен nil, однако, если я помещаю closure location.newLocation {} в инициализацию MiddlewareProvider, он публикует изменения местоположения. Почему в промежуточном программном обеспечении это ноль?
Я включил промежуточное программное обеспечение Firebase и журналирования, чтобы показать работающее промежуточное программное обеспечение:
class VMiddlewareProvider: MiddlewareProvider {
private var location: TrackLocation
init() {
self.location = TrackLocation()
}
func provideMiddleware() -> [Middleware<FluxState>] {
return [
loggingMiddleware(),
locationTrackingMiddleware(),
firebaseMiddleware()
]
}
private func loggingMiddleware() -> Middleware<FluxState> {
let loggingMiddleware: Middleware<AppState> = { dispatch, getState in
return { next in
return { action in
#if DEBUG
let name = __dispatch_queue_get_label(nil)
let queueName = String(cString: name, encoding: .utf8)
print("#Action: \(String(reflecting: type(of: action))) on queue: \(queueName ?? "??")")
#endif
return next(action)
}
}
}
return loggingMiddleware
}
private func locationTrackingMiddleware() -> Middleware<FluxState> {
let middleware: Middleware<AppState> = { dispatch, getState in
return { next in
return { action in
switch action as? LocationAction {
case .trackLocation:
self.location.newLocation = { result in
/// never gets called because newLocation is nil
print(result)
}
return next(action)
default:
return next(action)
}
return next(action)
}
}
}
return middleware
}
private func firebaseMiddleware() -> Middleware<FluxState> {
let firebaseMiddleware: Middleware<AppState> = { dispatch, getState in
return { next in
return { action in
switch action {
case let action as AccountActions.Authenticate:
let handle = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
return next(AccountActions.AuthentificationAction(isLoggedIn: true, userUID: user.uid))
} else {
return next(AccountActions.AuthentificationAction(isLoggedIn: false, userUID: nil))
}
}
default:
return next(action)
}
}
}
}
return firebaseMiddleware
}
}
Класс TrackLocation выглядит следующим образом:
class TrackLocation: NSObject {
let locationManager = CLLocationManager()
var newLocation: ((CLLocation)->())?
override init() {
super.init()
askForPermission()
locationManager.delegate = self
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startMonitoringVisits()
}
func checkAuthorisation() {
askForPermission()
}
func askForPermission() {
locationManager.requestWhenInUseAuthorization()
}
}
extension TrackLocation: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {
if let location = manager.location {
newLocation?(location)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
newLocation?(locations.last!)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print(status)
}
}