1

第一:抱歉标题不好。我不知道如何更好地描述我的问题。

我的 Xcode 项目中有这个代码:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    var currentLocation = "PLACEHOLDER"

    override func viewDidLoad() {
        self.locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        super.viewDidLoad()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        currentLocation = String(locValue.latitude)
    }
    @IBAction func sendLocation() {
        locationManager.startUpdatingLocation()
        print(currentLocation)
        locationManager.stopUpdatingLocation()
    }
}

这会在单击 UIButton 时打印用户位置。

这是有效的。但是由于某种原因,在重新启动应用程序后第一次按下 UIButton 时,它会打印PLACEHOLDER而不是位置。

意味着:当我启动应用程序并单击 UIButton 三次时,我在控制台中得到了这个:

PLACEHOLDER
56.153666216328625
56.153666216328625

而不是这个:

56.153666216328625
56.153666216328625
56.153666216328625

我也尝试存储 asUserDefaults而不是 as var,但这会导致同样的问题。

我究竟做错了什么?

4

2 回答 2

3

问题是位置更新是异步接收的,因此您在currentLocation新位置更新触发委托调用之前打印值,locationManager(_:, didUpdateLocations)因此您的currentLocation变量在更新之前打印。您需要在委托方法中打印值以显示更新的值。

顺便说一句,如果您想接收单个位置更新,则不应使用startUpdatingLocationandstopUpdatingLocation紧随其后,尤其是因为由于异步性,您实际上可能会在单个更新发生之前停止更新。您应该requestLocation用于接收一次性位置更新。此外,您应该locations在委托调用中使用变量,而不是manager.location.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let coordinate = locations.last?.coordinate else { return }
    currentLocation = String(coordinate.latitude)
    print(currentLocation)
}

@IBAction func sendLocation() {
    locationManager.requestLocation()
}
于 2019-01-09T11:41:49.117 回答
0

位置更新是异步发送给您的,因此您无法在调用 startUpdatingLocation() 后立即打印 currentLocation。

只需将打印件放入委托中

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    currentLocation = String(locValue.latitude)
    print(currentLocation) // print only after updating the location
}

它应该可以工作

于 2019-01-10T17:31:32.927 回答