我正在尝试创建一个LocationManager类来处理所有的GPS数据.我需要多个视图控制器中的GPS数据.问题是函数被调用但我没有得到坐标.我在状态栏中看到了GPS图标,但几秒后就消失了. GPSTracke
GPSTrackerManager.swift class GPSTrackingManager: NSObject, CLLocationManagerDelegate { var locationManager: CLLocationManager! var seenError : Bool = false func startTracking() { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() if ((error) != nil) { if (seenError == false) { seenError = true print(error) } } } func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) { //println("locations = \(locationManager)") var latValue = locationManager.location.coordinate.latitude var lonValue = locationManager.location.coordinate.longitude println(latValue) println(lonValue) } }
我如何在VC中的ViewDidLoad中调用它:
var tracking = GPSTrackingManager() tracking.startTracking()您在viewDidLoad方法完成后声明它将立即消失的方式,因为它的范围是方法的本地范围.您需要跟踪视图控制器的属性,以便它可以保持:
class ViewController: UIViewController { var tracking = GPSTrackingManager() override func viewDidLoad() { super.viewDidLoad() // ... tracking.startTracking() } }