Josh O'Connor
Josh O'Connor

Reputation: 4962

Update location only once

I am adding a mapKit for my app, and I setting the middle of the map to be the persons current location, in lat and lng. I am able to get it working, however, it keeps updating every so often. I only want it to update once when the app is loaded, then not update anymore. Maybe update every 2 minutes. Here is my code:

func locationManager(manager: CLLocationManager!,
    didUpdateLocations locations: [AnyObject]!)
{
    var latestLocation = locations.last as! CLLocation


    let location = CLLocationCoordinate2D(latitude: latestLocation.coordinate.latitude, longitude: latestLocation.coordinate.longitude)
    let span = MKCoordinateSpanMake(0.015, 0.015)

    //Let our point be the center of our span
    //region holds value of span and location
    let region = MKCoordinateRegion(center: location, span: span)

    //set up region on mapView
    mapView.setRegion(region, animated: true)

    //MKPointAnnotation defines a concrete annotation
    let annotation = MKPointAnnotation()
}

Upvotes: 0

Views: 1080

Answers (2)

MirekE
MirekE

Reputation: 11555

If you are targeting only iOS 9, look at the new requestLocation() method. It addresses your problem. If you need to target older versions of iOS, you could add stopMonitoringLocation() to the

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

This will stop the monitoring once you get one reading...

Upvotes: 5

dudeman
dudeman

Reputation: 1136

I'm not sure what your starting you location manager with, but I think you might want to look at using:

startMonitoringSignificantLocationChanges()

to start your location manager. Here is apple's documentation on the subject: https://developer.apple.com/library/prerelease/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html#//apple_ref/occ/instm/CLLocationManager/startMonitoringSignificantLocationChanges

Upvotes: 1

Related Questions