我在设置包中创建了“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()
}
}
最佳答案
View Controller 不响应应用程序状态。这是 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
关于ios - 返回 App 时如何读取设置包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148418/