使用 Swift 获取用户面对的方向

Getting the direction the user is facing using Swift

我试图以标签上显示的 N、S、E、W、NE、SE、SW、NW 的形式向用户指示他所面对的方向。每当用户改变他的物理方向时,标签将更新为当前方向。

有什么建议吗?

Swift 5.2

您可以使用 CoreLocation 框架执行此操作。

  1. 遵守CLLocationManagerDelegate协议
  2. 实例化CLLocationManager的一个实例并将委托设置为self
  3. 如果您只需要标题(而不是实际的用户位置),则不需要用户权限
  4. 告诉 CLLocationManager 开始更新标题
  5. 标题将被报告回委托方法didUpdateHeading
  6. 使用 switch 语句根据输入的度数查找基本方向。
  7. 更新您的标签

import CoreLocation
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    
    @IBOutlet var directionLabel: UILabel!

    var locationManager: CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.startUpdatingHeading()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        directionLabel.text = cardinalValue(from: newHeading.trueHeading)
    }
    
    func cardinalValue(from heading: CLLocationDirection) -> String {
        switch heading {
        case 0 ..< 22.5:
            return "N"
        case 22.5 ..< 67.5:
            return "NE"
        case 67.5 ..< 112.5:
            return "E"
        case 112.5 ..< 157.5:
            return "SE"
        case 157.5 ..< 202.5:
            return "S"
        case 202.5 ..< 247.5:
            return "SW"
        case 247.5 ..< 292.5:
            return "W"
        case 292.5 ..< 337.5:
            return "NW"
        case 337.5 ... 360.0:
            return "N"
        default:
            return ""
        }
    }
}

可以通过 .magneticHeading.trueHeading

访问代表的标题

Magnetic Heading

The value in this property represents the heading relative to the magnetic North Pole, which is different from the geographic North Pole. The value 0 means the device is pointed toward magnetic north, 90 means it is pointed east, 180 means it is pointed south, and so on. The value in this property should always be valid.

True Heading

The value in this property represents the heading relative to the geographic North Pole. The value 0 means the device is pointed toward true north, 90 means it is pointed due east, 180 means it is pointed due south, and so on. A negative value indicates that the heading could not be determined.