EricDXS
EricDXS

Reputation: 882

Swift: LocationManager in different class

I am trying to create a LocationManager class to handle all the GPS data. I need that GPS data in multiple view controllers. The problem is that the function is called but i don't get coordinates back. I am seeing the GPS icon in the statusbar, 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)

    }
}

How I call it in ViewDidLoad in my VC:

var tracking = GPSTrackingManager()
tracking.startTracking()

Upvotes: 4

Views: 2988

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

The way you're declaring that it will disappear right after your viewDidLoad method is finished, because its scope is local to the method. You need to make tracking a property of your view controller so it will stick around:

class ViewController: UIViewController {
    var tracking = GPSTrackingManager()

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

Upvotes: 4

Related Questions