Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLLocationManagerDelegate methods not being called in Swift code

I'm trying to create a simple app that finds out the region someone is in, but I'm stuck because none of the CLLocationManagerDelegate methods are called when the app runs and finds locations.

In case it's relevant I'm also not seeing the dialog asking that I give the app permission to use location.

Here's what I have so far -

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var locationLabel : UILabel!

var locationManager = CLLocationManager()
let geocoder = CLGeocoder ()

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.

  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBest
  locationManager.startUpdatingLocation()
}

override func viewDidDisappear(animated: Bool) {
  locationManager.stopUpdatingLocation()
}

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

func locationManager(manager: CLLocationManager!, didUpdateLocations locations:  [AnyObject]!) {
  geocoder.reverseGeocodeLocation(locations.last as CLLocation, completionHandler: {(placemark, error) in
    if (error != nil) {
      println("Error")
    } else {
      let pm = placemark.first as CLPlacemark

      println(pm)
    }
  })
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println("Epic Fail")
  } 
}

I've put in breakpoints so I know the code is never called. I have gone in and manually turned on location services for the app while it's been running too.

like image 759
Mark Reid Avatar asked Oct 17 '14 22:10

Mark Reid


Video Answer


1 Answers

try calling

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)

instead of the delegate call you are making now... I had problems with:

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

aswell. But using the above delegate call fixed my issue.

Edit (didn't read the question properly...)

You never ask for permission, which is why you don't get a popup. Call the following: locationManager.requestWhenInUseAuthorization()

This is quite an important step, and your app won't work if you haven't asked the user for authorization of your app

It is also important that you add NSLocationWhenInUseUsageDescription to your .plist file if running iOS8.

Screenshot:

enter image description here

like image 119
Chris Avatar answered Nov 15 '22 07:11

Chris