菜鸟教程小白 发表于 2022-12-11 17:55:07

ios - 返回值时iOS问题中的线程


                                            <p><pre><code>class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var lat: Double! = 0.0
    var long: Double! = 0.0

    override func viewDidLoad() {
      super.viewDidLoad()
            self.findMyLocation()
            print(self.lat)
            print(self.long)
    }

    func findMyLocation() {
      self.locationManager = CLLocationManager()
      locationManager.requestAlwaysAuthorization()
      locationManager.delegate = self
      locationManager.desiredAccuracy = kCLLocationAccuracyBest
      locationManager.startMonitoringSignificantLocationChanges()

      locationManager.delegate = self
      locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
      locationManager.requestWhenInUseAuthorization()

      // Here we start locating
      locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: ) {
      for location in locations {
            self.lat = location.coordinate.latitude
            self.long = location.coordinate.longitude
      }
      locationManager.stopUpdatingLocation()
    }
}
</code></pre>

<p>这是我的简单 ViewController ,用于获取我当前位置的纬度和经度,并将其分配给局部变量 <code>lat</code> 和 <code>long</code> 然后 <code>print</code> 它。上面的代码总是为 <code>lat</code> 和 <code>long</code> 打印 0.0。这样做的原因是因为首先执行 <code>print(lat) print(long)</code>,然后执行获取位置。我确信有一些非常简单的方法可以解决这个问题,但我不知道该怎么做。任何帮助表示赞赏。我假设我们必须与大中央调度合作。请建议我应该看什么。 </p>

<p>另外,我已将 <code>NSLocationWhenInUseUsageDescription</code> 添加到 <code>info.plist</code>。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您只能在位置管理器找到一些坐标后打印坐标,即在函数<code>locationManager(manager: CLLocationManager, didUpdateLocations locations: )</code>中。<br/>
但是当位置管理器还没有坐标时,您尝试在 <code>viewDidLoad</code> 中打印它们。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 返回值时iOS问题中的线程,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40200054/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40200054/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 返回值时iOS问题中的线程