这很可能很容易解决,但我已经研究了一段时间,似乎无法得到答案。
我想知道为什么CLLocationManager
的委托方法直到ViewDidLoad
函数之后才触发,当CLLocationManager
加载到ViewDidLoad
函数中时。
我已在我的应用程序方案中将默认区域设置为澳大利亚悉尼,并将我的 locationManager 封装在其自己的类中,如下所示:
import UIKit
import CoreLocation
/* Class location is a class to track user location and return a location object. */
class usrLocation: NSObject, CLLocationManagerDelegate
{
//MARK: Properties
var locationMgr: CLLocationManager!
var location: CLLocation!
var seenError: Bool = false
//MARK: Public Methods
func startTracking() {
locationMgr = CLLocationManager()
locationMgr.delegate = self
locationMgr.desiredAccuracy = kCLLocationAccuracyBest
locationMgr.requestWhenInUseAuthorization()
locationMgr.startUpdatingLocation()
}
//Return a location object
func getLocation() -> CLLocation {
locationMgr.startUpdatingLocation()
return location!
}
//MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationMgr.stopUpdatingLocation()
if (seenError == false) {
seenError = true
print(error)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = (locations ).last
locationMgr.stopUpdatingLocation()
}
}
我已经在我的ViewController
中初始化了该类,并尝试开始跟踪我在viewDidLoad
的当前位置。
代码如下所示。
override func viewDidLoad() {
var location = usrLocation()
override func viewDidLoad() {
super.viewDidLoad()
// Track location
location.startTracking()
location.getLocation()
//update Label text
sLongitude.text = "(location.getLocation().coordinate.longitude)"
sLatitude.text = "(location.getLocation().coordinate.latitude)"
}
getLocation()
从不返回位置,因为它始终为 nil,因为委托didUpdateLocations
函数不运行。这是为什么呢?
我试图使用完成处理程序来工作,但不能,所以我的解决方案是忽略通过 viewDidLoad 设置标签文本,而是在设置位置变量后更新标签。这样,viewDidLoad 就完成了,委托被调用,标签被更新。
var location: CLLocation! {
didSet {
//update Label text
sLongitude.text = "(location.getLocation().coordinate.longitude)"
sLatitude.text = "(location.getLocation().coordinate.latitude)"
}
}