我创建了" updateheading"在设置包中
如果用户离开应用程序,请转到设置更改值,当用户返回应用程序时,locationManager应根据更新的值开始/停止。
但该应用程序未运行viewWillAppear。如何阅读更新值?
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()
}
}
答案 0 :(得分:2)
视图控制器不响应应用程序状态。它是AppDelegate的责任。但您可以订阅通知。
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
}
doUpdate是您当前的代码。
PS:"如果覆盖viewWillAppear,则必须在实施中的某个时刻调用super。" (c)Apple Docs