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

A. *_*amy 1 xcode core-location swift

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

有什么建议?

rba*_*win 5

斯威夫特 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 ""
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

来自委托的标题可以作为.magneticHeading.trueHeading

磁航向

此属性中的值表示相对于磁北极的航向,与地理北极不同。值 0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。此属性中的值应始终有效。

真实航向

此属性中的值表示相对于地理北极的航向。值 0 表示设备指向正北,90 表示指向正东,180 表示指向正南,依此类推。负值表示无法确定航向。