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

时间:2016-10-23 06:01:42

标签: ios multithreading grand-central-dispatch core-location

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

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