Swift: LocationManager in different classes

I am trying to create a class LocationManagerto handle all GPS data. I need GPS data in several controllers. The problem is that the function is being called, but I am not returning the coordinates. I see the GPS icon in the status bar, but it goes away after a few seconds.

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)

    }
}

As I call it in ViewDidLoadin my VC:

var tracking = GPSTrackingManager()
tracking.startTracking()
+4
source share
1 answer

As you declare, it will disappear right after the completion of your method viewDidLoad, since its scope is local to the method. You need to make a trackingproperty of your view controller so that it is around:

class ViewController: UIViewController {
    var tracking = GPSTrackingManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...
        tracking.startTracking()
    }
}
+3
source

All Articles