4

i have problem with getting my location with CLLocationDelegate. i created new subclass of UIView and work well, but when i created subclass of NSObject, CLLocationDelegate not called. I can find where is problem. here is my code:

import UIKit
import CoreLocation

class LocationData: NSObject, CLLocationManagerDelegate {

var locationManager : CLLocationManager = CLLocationManager()

override init() {
    super.init()
    if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
        self.locationManager.requestWhenInUseAuthorization()
    }
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    println("init LocationData")
}

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error.description)
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    println("updated")
    }
}

Thanks!

  • Have you looked at http://stackoverflow.com/questions/24062509/location-services-not-working-in-ios-8? –  Mar 19 '15 at 13:00

1 Answers1

4

Your code is fine! But when instantiating the class, you need to do like this:

 import UIKit

 class ViewController: UIViewController {

 let LocationData: LocationData = LocationData()  //<- here is the secret to works!!!

 override func viewDidLoad() {
      super.viewDidLoad()
}

I also suggest that you change your init to something like this:

override init() {
    super.init()

    let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

    if authorizationStatus == .notDetermined {
        locationManager.requestWhenInUseAuthorization()
    }

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    print("init LocationData")
}

And don't forget to add NSLocationWhenInUseUsageDescription in the info.plist project.

Carlos Irano
  • 682
  • 7
  • 8