【问题标题】:Getting the direction the user is facing using Swift使用 Swift 获取用户面临的方向
【发布时间】:2020-05-10 03:36:22
【问题描述】:

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

有什么建议吗?

【问题讨论】:

    标签: swift xcode core-location


    【解决方案1】:

    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 访问

    磁航向

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

    真航向

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

    【讨论】:

    • 如何处理 22.53 的标题?
    • 谢谢你!这正是我所需要的。但是当我尝试在操场上运行此代码时,函数 locationManager 永远不会被调用,并且标签不会显示任何内容。我该如何解决这个问题?
    • 并且您可以使用CLLocationManager.headingAvailable()检查您正在运行的任何设备上是否有可用的航向信息//返回布尔值
    • 我在 iPad 上的 Playgrounds 上运行它,CLLocationManager.headingAvailable() 返回 true。
    • 试试PlaygroundPage.current.needsIndefiniteExecution = true
    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2015-08-29
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    相关资源
    最近更新 更多