Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS的磁航向示例代码_Ios_Swift_Core Location - Fatal编程技术网

iOS的磁航向示例代码

iOS的磁航向示例代码,ios,swift,core-location,Ios,Swift,Core Location,有人能给我一个简短的片段,让我知道iPhone的磁头吗? 我不要Objective-C。我需要用Swift 到目前为止,我已经写了这些行,但它没有返回任何值: let locManager = CLLocationManager() locManager.desiredAccuracy = kCLLocationAccuracyBest locManager.requestWhenInUseAuthorization() locManager.startUpdatingLocation() l

有人能给我一个简短的片段,让我知道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)

谢谢

您没有为位置管理器设置代理。iOS不会立即更新您的位置。相反,当它有位置/标题更新时,它将调用委托提供的函数。这种设置背后的原因是效率。10个应用程序中有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)"
    }
}

非常感谢你的帮助。我花了几个小时在这上面。现在我有一个问题,当标题可用时,应用程序如何知道调用这3个函数中的哪一个?