Xitcod13 Xitcod13 - 3 months ago 10
iOS Question

Location Update not working

I am trying to make the location update happen even if the user exited the view going back to the previous view.
To make this happen i have created a separate class that handles my location update but I am encountering strange behavior.

First of all my authorization request was only popping up for a split second and than disappearing so i moved it back to the actual view.
However my location update is still not working.
The location icon appears on the device but it never enters the didLocationUpdate function. Neither is it entering didFailWithError.
I'm pretty new to iOS so i have no idea what im doing wrong.

Here is my class:

import CoreLocation

class RouteLocation: NSObject, CLLocationManagerDelegate{

var locationManager:CLLocationManager!

var databasePath = ""
override init(){

super.init()

let dirPaths =
NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)
let docsDir = dirPaths[0] as NSString

databasePath = docsDir.stringByAppendingPathComponent(
"\\firstAscent.db")

// For use in foreground
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()


// locationManager.requestAlwaysAuthorization()
// print("in location")

if CLLocationManager.locationServicesEnabled() {
print("System Services enabled")
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 10
self.locationManager.startUpdatingLocation()
}


}
var isLocationMising = true


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate

let latitute = locValue.latitude
let longitute = locValue.longitude
print("locations = \(locValue.latitude) \(locValue.longitude)") //continues to make SQL query calls


I call it from the view with:
_ = RouteLocation()

Answer
  1. The requestWhenInUse... function runs asynchronously. It will show the dialog, but continue processing the rest of the code at the same time. Your app won't run correctly the first time (when the permission is given) even if everything else is correct.
  2. Did you provide the requestWhenInUseAuthorization explanation string?
  3. I think the way you instantiate the class it runs the init and instantly dies. There is nothing to retain it. Therefore the didUpdateLocation can't be called.
  4. If you need just one location, call requestLocation.