LiTHiUM2525
LiTHiUM2525

Reputation: 307

Swift 2 : iOS 8+ How to store latitude/longitude with CoreLocation and stop locating

Yeah ! My CoreLocation working now ! So i have a problem to store latitude and longitude and stopping locating.

I have a Sign In page (my MainVC)

before user sign in i need to get and store current device location and stop locating (now it's working with help of Alexander see under).

in my MainVC.swift i have this 2 global variables

    var locationManager:CLLocationManager!
    var myLocations = [CLLocation]()

in my viewDidLoad() i have this :

        //Setup our Location Manager
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()

For operate locationManager i have this 2 functions :

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print("locations = \(locations)")
    errorMsgIfInternetNotAvailable.text = "GPS success"

    myLocations.append(locations.last!)

    locationManager.stopUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    errorMsgIfInternetNotAvailable.text = "Error while updating location " + error.localizedDescription
}

When i build my app, all working, if not autorise my device to get GPS informations i have the locationManager function error working.

If i autorise it

in console, the location update every second and don't stop it with the .stopUpdatingLocation() command

Upvotes: 1

Views: 703

Answers (1)

Alexander Perechnev
Alexander Perechnev

Reputation: 2837

First, it is always good to provide the build error output. It's hard enough to guess which error you're getting.

It seems like you defined, but not initialized myLocations property. You have to do it like this:

var myLocations = [CLLocation]()

Notice the brackets () in initialization.

And then you have to add object to your array:

myLocations.append(locations.last)

or, if you want to store only one object in your array, do it like:

myLocations = [locations.last]

Upvotes: 2

Related Questions