iOS 磁性航向示例代码

jim*_*mes 3 core-location ios swift

谁能给我一个简短的片段,让我返回 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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Cod*_*ent 5

您没有为位置管理器设置委托。iOS 不会立即更新您的位置。相反,当它具有位置/航向更新时,它将调用您的委托提供的函数。这种设置背后的原因是效率。与有 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)"
    }
}
Run Code Online (Sandbox Code Playgroud)