ios - iOS 磁航向示例代码

标签 ios swift core-location

谁能给我提供一个简短的片段,让我返回 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/

相关文章:

iphone - 如何在 IOS 中保存或导出 640 x 640 分辨率的视频?

swift - CLLocationCoordinate2D 不符合预期的字典值类型 'AnyObject'

iphone - iOS:已授予权限?

ios - 在后台监控 iBeacon 信标

ios - Swift 上的 "Fatal error: Unexpectedly found nil while unwrapping an Optional value"和 JSON

ios - ios:大量数据库记录-可能吗?

ios - 使用 Swift 在 iOS 中使用 userDefaults 检查应用程序设置

swift - NSLocale.currentLocale 的端口方法 swizzle 从 swift 2.3 到 swift 3

ios - 线程 1 : signal SIGABRT;0_abort_with_payload when run on iPhone Swift 4. 1

swift - 类型 'StorageReference' 的值没有成员 'put'