gpt4 book ai didi

ios - RxSwift 和 CLLocation : crash when trying to get user location

转载 作者:行者123 更新时间:2023-11-28 08:39:20 25 4
gpt4 key购买 nike

我在我的应用程序中使用 RSwift 库。我正在尝试获取用户位置以便在网络请求中发送它。要获取此位置,我需要使用 Observables,因为如果用户未授权位置,该函数必须抛出错误。

该算法是许多 Observable 的连接数组的一部分,这些 Observable 在主线程之外的另一个线程中运行(为了不卡住 UI)。我需要在主线程中执行“获取用户位置”功能,因为如果不在主线程中执行它会崩溃并且崩溃日志是:

fatal error: Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread

在上面的代码中,有地理定位助手初始化(这是一个单例)和执行获取用户位置(或错误)的方法。

private var authorized: Observable<Bool?>
private var location: Observable<CLLocationCoordinate2D>
private let locationManager = CLLocationManager()

private init() {
locationManager.desiredAccuracy = LocationOptions.desiredAccuracy

authorized = Observable.just(false)
.map({ _ in CLLocationManager.authorizationStatus() })
.concat(locationManager.rx_didChangeAuthorizationStatus)
.distinctUntilChanged()
.map({ authorizedStatus in
switch authorizedStatus {
case .AuthorizedAlways, .AuthorizedWhenInUse:
return true
case .NotDetermined:
return nil
case .Restricted, .Denied:
return false
}
})
.catchErrorJustReturn(false)

location = locationManager.rx_didUpdateLocations
.filter { $0.count > 0 }
.map({ return $0.last!.coordinate })
}


func getLocation() -> Observable<Location> {
return authorized
.flatMap({ authorized -> Observable<CLLocationCoordinate2D> in
guard let authorized = authorized else {
self.locationManager.requestAlwaysAuthorization()
return Observable.empty()
}

if authorized {
self.startUpdating()
return self.location
} else {
return Observable.error(
NSError(
domain:"",
code: 0,
userInfo:nil )
)
}
})
// We just need one position updated
.take(1)
.map({ coordinate in
self.stopUpdating()

let location = Location(longitude: coordinate.longitude, latitude: coordinate.latitude, latestUpdatedDate: NSDate())
if location.isValid() {
saveLocation(location)
}
return location
})
.doOnError({ error in self.stopUpdating() })
}

我在 RXSwift 地理定位示例 ( https://github.com/ReactiveX/RxSwift/pull/429 ) 中看到一个可以使用 Drivers 处理它的类,但我确实需要有一个错误,而 Drivers 不能返回错误。

如果有人可以帮助我实现这一目标,我将不胜感激。

我已经尝试将“.observeOn(MainScheduler.instance)”添加到 2 个可观察对象,但它卡住了 UI。也许有更好的方法可以在不卡住 UI 的情况下执行此操作。

谢谢

最佳答案

@romroll,DelegateProxy 目前仅在 RxCocoa 的主线程上工作。尝试做这样的事情

.map({ _ in CLLocationManager.authorizationStatus() })
.observeOn(MainScheduler.instance)
.concat(locationManager.rx_didChangeAuthorizationStatus)
.observeOn(someOtherScheduler)
.distinctUntilChanged()

希望这对您有所帮助。如果没有,您可以随时通过 RxSwiftSlack 联系我,通过提及@sergdort 或其他人 :)

关于ios - RxSwift 和 CLLocation : crash when trying to get user location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com