Swift

iOS RxSwift GPS

반다이크 2022. 5. 12. 09:44
반응형

RxSwift GPS Manager

class LocationPermissionManager {
    static let shared = LocationPermissionManager()
    private let disposeBag = DisposeBag()
    
    let locationSubject = BehaviorSubject<CLLocationCoordinate2D?>(value: nil)
    private let locationManager: CLLocationManager = {
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter = kCLDistanceFilterNone
        return manager
    }()
    
    private init() {
        self.locationManager.rx.didUpdateLocations
            .compactMap(\.locations.last?.coordinate)
            .bind(onNext: self.locationSubject.onNext(_:))
            .disposed(by: self.disposeBag)
        self.locationManager.startUpdatingLocation() // 이미 권한을 허용한 경우 케이스 대비
    }
    
    func requestLocation() -> Observable<CLAuthorizationStatus> {
        return Observable<CLAuthorizationStatus>
            .deferred { [weak self] in
                guard let auth = self else { return .empty()}
                auth.locationManager.requestWhenInUseAuthorization()
                return auth.locationManager.rx.didChangeAuthorization
                    .map { $1 }
                    .filter { $0 != .notDetermined }
                    .do(onNext: { _ in auth.locationManager.startUpdatingLocation()})
                        .take(1)
            }
    }
    
    
}


# 실시간 구독

  //   GPS
        LocationPermissionManager.shared.locationSubject
            .bind(onNext: { gps in
                print("gps: ",gps)
                
            }).disposed(by: disposebag)
   //  GPS 권한
        LocationPermissionManager.shared.requestLocation()
           .bind {
               print("auth: ",$0)
           }
           .disposed(by: self.disposebag)
반응형

'Swift' 카테고리의 다른 글

RxSwift + Alamofire  (0) 2022.07.14
iOS ScrollView 설정  (0) 2022.06.05
iOS 분리된 타겟 내부 XML 파일 파싱  (0) 2022.05.02
iOS GoogleService - Info 타겟 분리(FCM, Crashlytics)  (0) 2022.05.02
iOS 타겟 분리  (2) 2022.05.02