OGeek|极客世界-中国程序员成长平台

标题: ios - 返回值时iOS问题中的线程 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:55
标题: ios - 返回值时iOS问题中的线程

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: [CLLocation]) {
        for location in locations {
            self.lat = location.coordinate.latitude
            self.long = location.coordinate.longitude
        }
        locationManager.stopUpdatingLocation()
    }
}

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

另外,我已将 NSLocationWhenInUseUsageDescription 添加到 info.plist



Best Answer-推荐答案


您只能在位置管理器找到一些坐标后打印坐标,即在函数locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])中。
但是当位置管理器还没有坐标时,您尝试在 viewDidLoad 中打印它们。

关于ios - 返回值时iOS问题中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200054/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4