谁能给我提供一个简短的片段,让我返回 iPhone 的磁航向? 我不要 Objective-C。我在 Swift 中需要它。
到目前为止我已经写了这些行,但它没有返回任何值:
let locManager = CLLocationManager()
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.requestWhenInUseAuthorization()
locManager.startUpdatingLocation()
locManager.startUpdatingHeading()
locManager.headingOrientation = .portrait
locManager.headingFilter = kCLHeadingFilterNone
print(locManager.heading?.trueHeading.binade as Any)
谢谢!
最佳答案
您没有为位置管理器设置委托(delegate)。 iOS 不会立即更新您的位置。相反,当它有位置/标题更新时,它将调用您的委托(delegate)提供的函数。这种设置背后的原因是效率。这 10 个位置管理器将请求在 GPS 有更新时收到通知,而不是 10 个应用程序有 10 个不同的位置管理器在 GPS 硬件上竞争时间。
试试这个:
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var label: UILabel!
var locManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.requestWhenInUseAuthorization()
locManager.headingOrientation = .portrait
locManager.headingFilter = kCLHeadingFilterNone
locManager.delegate = self // you forgot to set the delegate
locManager.startUpdatingLocation()
locManager.startUpdatingHeading()
}
// MARK: -
// MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location Manager failed: \(error)")
}
// Heading readings tend to be widely inaccurate until the system has calibrated itself
// Return true here allows iOS to show a calibration view when iOS wants to improve itself
func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool {
return true
}
// This function will be called whenever your heading is updated. Since you asked for best
// accuracy, this function will be called a lot of times. Better make it very efficient
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
label.text = "\(newHeading.magneticHeading)"
}
}
关于ios - iOS 磁航向示例代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080571/