Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

RxSwift 超入門その3

class GeolocationViewController: ViewController {
    
    @IBOutlet weak private var noGeolocationView: UIView!
    @IBOutlet weak private var button: UIButton!
    @IBOutlet weak private var button2: UIButton!
    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // No GeoLocation Viewを追加する
        view.addSubview(noGeolocationView)
        
        let geolocationService = GeolocationService.instance
        
        // GeoLocation が利用できる場合は No GeoLocation Viewを隠す
        geolocationService.authorized
            .drive(noGeolocationView.rx.isHidden)
            .disposed(by: disposeBag)
        
        // ロケーションが変化したら、座標ラベルを更新する
        geolocationService.location
            .drive(label.rx.coordinates)
            .disposed(by: disposeBag)
        
        // No GeoLocation Viewにあるプリファレンスオープンボタン
        button.rx.tap
            .bindNext { [weak self] in
                self?.openAppPreferences()
            }
            .disposed(by: disposeBag)
        
        // GeoLocation Viewにあるプリファレンスオープンボタン
        button2.rx.tap
            .bindNext { [weak self] in
                self?.openAppPreferences()
            }
            .disposed(by: disposeBag)
    }
    
    private func openAppPreferences() {
        UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
    }
}