在视图控制器viewDidLoad函数完成之前,CoreLocation Delegate函数不会运行

时间:2017-01-13 05:04:57

标签: ios swift core-location

这很可能很容易解决,但我已经有一段时间了,并且似乎无法得到答案。

我想知道为什么在ViewDidLoad函数中CLLocationManager加载ViewDidLoad之后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的委托方法才会触发。

我已经在我的App Scheme中将我的默认区域设置为Sydney Australia,并且我将locationManager封装在它自己的类中,如下所示:

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()中开始跟踪我当前的位置。

代码看起来像这样。

didUpdateLocations

def clean_list(lst): i = 0 while i < len(lst): item = lst[i] # item to check j = i + 1 # start next item along while j < len(lst): if item == lst[j]: lst.pop(j) else: j += 1 i += 1 values = [1, 2, 0, 1, 4, 1, 1, 2, 2, 5, 4, 3, 1, 3, 3, 4, 2, 4, 3, 1, 3, 0, 3, 0, 0] clean_list(values) print(values) # Output [1, 2, 0, 4, 5, 3] 永远不会返回位置,因为它始终为nil,因为委托def clean_list(lst): seen = set() i = 0 while i < len(lst): item = lst[i] if item in seen: lst.pop(i) else: seen.add(item) i += 1 values = [1, 2, 0, 1, 4, 1, 1, 2, 2, 5, 4, 3, 1, 3, 3, 4, 2, 4, 3, 1, 3, 0, 3, 0, 0] clean_list(values) print(values) # Output [1, 2, 0, 4, 5, 3] 函数不会运行。为什么是这样?

1 个答案:

答案 0 :(得分:0)

我试图使用完成处理程序来完成这项工作,但是我的解决方案是忽略通过viewDidLoad设置标签文本,而是在设置了位置变量后更新标签。这样viewDidLoad就完成了,调用委托并更新标签。

var location: CLLocation! {

didSet {
    //update Label text
    sLongitude.text = "\(location.getLocation().coordinate.longitude)"
    sLatitude.text = "\(location.getLocation().coordinate.latitude)"    
}

}