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

标签 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()
    }
}

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

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

最佳答案

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

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

相关文章:

ios - Swift - Grand Central Dispatch 与 block /闭包

ios - 从字符串中提取货币和价格值

ios - Swift 子类与协议(protocol)

IOS Segue 在自定义选项卡栏中不起作用

multithreading - 链式2 future -计算一个并返回另一个

objective-c - dispatch_async() 和类似的东西是否提供内存栅栏?

ios - 无法使具有标识符 cellID 的单元格出队。相同的代码在旧的 Swift 上运行良好

java - 线程池并行处理消息,但保留对话中的顺序

c++ - 类构造函数可以永远阻塞吗?

ios - dispatch_queue_t 和 TableView