4

I am getting the users current location and dropping this as a println(). The idea is that I am going to hit a button to get the new location, however currently the app keeps updating constantly (every second) instead. I have tried moving the getLocation() function inside my IBAction but that crashed the thing. I have updated the info.plist so thats not a problem. Heres le code:

    import UIKit
import CoreLocation


class ViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet var latitude : UILabel!
    @IBOutlet var longitude : UILabel!

    var locationManager = CLLocationManager()
    var startLocation: CLLocation!


    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func findMyLocation(sender: AnyObject){
        startLocation = nil
        locationManager.startUpdatingLocation()

    }

    func getLocation(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){

        var userLocation:AnyObject = locations[0] as! CLLocation

        var strlat = String(format: "%.4f", userLocation.coordinate.latitude)
        var strlong = String(format: "%.4f",userLocation.coordinate.longitude)

        latitude.text = String(format: "%.4f", userLocation.coordinate.latitude)
        longitude.text = String(format: "%.4f",userLocation.coordinate.longitude)

        println("latitude: " + strlat)
        println("longitide: " + strlong)

        if startLocation == nil {
            startLocation = userLocation as! CLLocation
            locationManager.stopUpdatingLocation()
        }



    }

    func locationManager(manager: CLLocationManager!,
        didFailWithError error: NSError!) {

    }
}
Saucepan
  • 298
  • 1
  • 6
  • 19
  • you could call your locationManager stopUpdatingLocation method to stop the location update.So, once you get location you can stop updating location. – Sandeep Aug 03 '15 at 14:46
  • @GeneratorOfOne good point! but how would i implement that in the findMyLocation function? I would still like to have that function get the new location after I moved... – Saucepan Aug 03 '15 at 15:02
  • Are you looking for `startMonitoringSignificantLocationChanges` instead? – Larme Aug 03 '15 at 15:22
  • @Larme no, rather just wanting an snap shot location of the current location when the button is pressed – Saucepan Aug 03 '15 at 15:26

1 Answers1

8

Move the locationManager.startUpdatingLocation() to your findMyLocation function. This will start the locationManager when your button is pressed and begin calling the didUpdateLocations Inside your if startLocation == nil add locationManager.stopUpdatingLocation() this will stop the locationManager after you have set your startLocation var. Every time the user presses the button the process will run again.

One additional note, you should add more code into the didUpdateLocations to check the accuracy and timestamp of the location before you use it as it may not be a valid/accurate location for what you are trying to do.

UPDATE:

Had a chance to validate and the code will work with the changes suggested. Here is what your final code should look like. I am also assuming you have set your plist entries for locations services and your simulator is set to simulate locaitons.

import UIKit
import CoreLocation


class ViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet var latitude : UILabel!
    @IBOutlet var longitude : UILabel!

    var locationManager : CLLocationManager! = CLLocationManager()
    var startLocation: CLLocation!


    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func findMyLocation(sender: AnyObject){
        startLocation = nil
        locationManager.startUpdatingLocation()

    }

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

        var userLocation:AnyObject = locations[0] as! CLLocation

        var strlat = String(format: "%.4f", userLocation.coordinate.latitude)
        var strlong = String(format: "%.4f",userLocation.coordinate.longitude)

        latitude.text = String(format: "%.4f", userLocation.coordinate.latitude)
        longitude.text = String(format: "%.4f",userLocation.coordinate.longitude)

        println("latitude: " + strlat)
        println("longitide: " + strlong)

        if startLocation == nil {
            startLocation = userLocation as! CLLocation
            locationManager.stopUpdatingLocation()
        }



    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {

        println("error with location manager: " + error.description)

    }


}
rmp
  • 3,503
  • 1
  • 17
  • 26
  • sorry, but that did not work at all - the app doesnt even execute the getLocation function anymore. I am not sure the startUpdatingLocation is reached from where you suggested. – Saucepan Aug 03 '15 at 15:32
  • Can you update your question to show what you changed? This is pretty standard stuff so I'm not sure what is not working. also try declaring your locationManager only once, not in the viewDidLoad too. – rmp Aug 03 '15 at 15:38
  • sure. i just updated the code above. it builds fine, but when i press the findMyLocation button nothing happens. – Saucepan Aug 03 '15 at 15:41
  • You don't need a custom function for the location updates – rmp Aug 03 '15 at 15:44
  • I know i dont need it - but i want it. Thats the issue. I want to press the button and get the coordinates updated in my IBOutlets – Saucepan Aug 03 '15 at 15:46
  • starting and stopping the locationManager will automatically call `func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!)` delegate so that will do what you need. – rmp Aug 03 '15 at 15:48
  • but it is not though... when i call it, by pressing the button, nothing happens. if i move the function outside the button and automatically start it then the location updates, however this is not what i want to do - thus the problem – Saucepan Aug 03 '15 at 15:54
  • did you change your 'getLocation` to the standard `func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!)` ? – rmp Aug 03 '15 at 15:58
  • @Saucepan this code should work. I agree with rmp - there is no need to have custom function. When you press the button again your location manager will perform the update of location again and will finish by calling the standard delegate function. You can repeat this process as many times as you want without problems. If you do have problems then paste the complete code - there must be an error somewhere else – Andriy Gordiychuk Aug 03 '15 at 23:27
  • @rmp i copied the code above and it did work, however i have no ide what i was doing wrong... i tried looking over the code comparing to mine, but i cant figure out where i sidestepped. probably something stupid staring me in the face, i just cant see it - thank you for all the help! – Saucepan Aug 04 '15 at 11:00
  • Glad you got it working. The two main changes to your code, as mentioned in my comments, were 1) only declare the var locationManager once (not twice as you were doing) 2) use the delegate method `funct locationManager` and not your custom function `getLocation` . Hope that helps. – rmp Aug 04 '15 at 14:46
  • @rmp I have a very similar issue but with reverseGeocode...is there any chance you could kindly take a look at my post and if possible, help me out? Thanks in advance! **my SO post** [link](http://stackoverflow.com/questions/34033506/swift-locationmanager-looping-through-multiple-times/34033812#34033812) – Matty Dec 02 '15 at 05:22