DidUpdateLocation不存储位置,userLoc始终为零

时间:2018-06-22 22:46:21

标签: swift cllocationmanager

我试图简单地获取用户的当前设备位置并将其存储在名为userLoc的全局变量中。我有这段代码可以调用didUpdateLocation:

self.locationManager.requestLocation()
print("aaa ", self.userLoc)

,并将userLoc设置为当前位置:

func locationManager(_ manager: CLLocationManager,
                         didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            self.userLoc = location
        }
    }

userLoc的定义如下:

var userLoc: CLLocation?

但是当我运行该应用程序并尝试打印userLoc时,它始终会打印:

aaa nil

Privacy - Location When In Use Usage Description在Info.plist中设置。老实说,我不知道还能尝试什么。我一直在想办法解决这个问题。您能提供的任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

这是我要在视图控制器类中获取用户位置的方法。我认为您缺少locationManager.startUpdatingLocation()

var currentLocation: CLLocationCoordinate2D!
var locationManager: CLLocationManager = CLLocationManager()

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
currentLocation = locationManager.location!.coordinate