0

I created "updateheading" in settings bundle

If user leave the app, go to setting to change value, when user go back the app, locationManager should start/stop base on the updated value.

But the app does not run viewWillAppear. How to read updated value?

private let locationManager : CLLocationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.requestWhenInUseAuthorization()
    locationManager.delegate = self
}
override func viewWillAppear(_ animated: Bool) {

    let userDefault = UserDefaults.standard
    let updateheading = userDefault.object(forKey: "updateheading") as! Bool
    if(updateheading){
        locationManager.startUpdatingHeading()
    }else{
        locationManager.stopUpdatingHeading()
    }
}
CL So
  • 3,647
  • 10
  • 51
  • 95
  • Let me get that clear, you have a settings bundle, right? If so, how are you reading from that bundle? – Ashraf Tawfeeq Jan 08 '18 at 10:48
  • yes, I have a settings bundle `Root.plist`, and I use this to read the value in bundle `let updateheading = userDefault.object(forKey: "updateheading") as! Bool` – CL So Jan 08 '18 at 11:06
  • I think your answer might be here https://stackoverflow.com/questions/6291477/how-to-retrieve-values-from-settings-bundle-in-objective-c – Ashraf Tawfeeq Jan 08 '18 at 13:10

1 Answers1

2

View controller do not responding on application state. It is responsibility of AppDelegate. But you can subscribe for notifications.

var observer: Any?

override func viewWillAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    observer = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) { (_) in
        doUpdate()
    }
    doUpdate()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    observber = nil
}

Where doUpdate is your current code.

PS: "If you override viewWillAppear, you must call super at some point in your implementation." (c) Apple Docs

MichaelV
  • 1,231
  • 8
  • 10