【问题标题】:Users lat long in ViewDidLoadViewDidLoad 中的用户 lat long
【发布时间】:2023-03-24 18:17:01
【问题描述】:

如何在viewDidLoad方法中引用用户当前的经纬度值?

我尝试过使用以下方法,但是...

   let locationManager = CLLocationManager()

    override func viewDidLoad()    
{
        super.viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

        self.mapView.showsUserLocation = true
        mapView.delegate = self
        let locationLong = locationManager.location!.coordinate.longitude
        ...

我认为 locationManager 在代码运行之前没有机会获得该值,并且它失败并显示以下消息:

致命错误:在展开可选值时意外发现 nil

【问题讨论】:

  • 如果你不知道如何使用一个类,为什么不阅读它的文档呢?
  • 获取用户位置可能需要几秒钟,所以是的,当您尝试访问主线程上的值时它是 nil...
  • 你需要使用CLLocationManager委托方法来获取坐标,你做错了什么。阅读文档。
  • 我们要做的是在应用程序打开后立即向用户显示前往目的地的路线。有没有办法做到这一点,它不在主线程上,或者以某种方式依赖于 CCLocationManager 完成确定用户位置?
  • 应该可以了,你在plist中添加了位置权限请求吗??

标签: ios swift mapkit cllocationmanager


【解决方案1】:

我在这里找到了我想要的答案:

Nil when obtain coordinates in swift

作为一般规则,除非位置服务已启动并且位置更新已经开始进入(例如,您已经看到调用了 didUpdateLocations),否则您不应期望位置属性有一个有效的 CLLocation 对象。确定位置的过程是异步发生的,预计不会在 viewDidLoad 中可用。应该将特定位置的逻辑放在 didUpdateLocations 方法中。

【讨论】:

    【解决方案2】:

    请尝试以下代码。希望这对你有用。谢谢

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    
        self.mapView.showsUserLocation = true
        mapView.delegate = self
    }
    
    // CLLocationManager Delegate Method
    func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
          //Use manager for latitude and longitude
    }
    

    【讨论】:

    • 感谢您的回复。我们正在尝试访问 viewDidLoad 方法中的 lat 和 long 值。听起来这不是最佳方式,但我不知道如何在应用打开后立即向用户显示路线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多