在返回值时在iOS问题中线程化

问题描述 投票:2回答:2
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()
    }
}

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

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

ios multithreading grand-central-dispatch core-location
2个回答
0
投票

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


0
投票

您必须习惯异步操作的工作方式。他们在未来的某个时刻提供他们的结果。

使用CLLocation时,用户可能会拒绝您获取该位置的权限。只是因为你想要的位置并不意味着你得到它。

因此,您的视图必须能够在所有三种情况下显示有用的内容:位置尚未知晓,位置被拒绝,位置已知。并且您希望实现didChangeAuthorizationStatus,以防您的状态从“未知”更改为“拒绝访问”。每个回调必须能够适当地改变显示。

© www.soinside.com 2019 - 2024. All rights reserved.