Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Eric Whittaker
2,974 PointsCoreLocation Project - Print My Location
team,
I cant quite figure out why this code doesn't print my location in the output area of XCode. I can get it to prompt to look for my location in the iOs sim, but after that, nothing. Any help?
import UIKIT
import MapKit
import CoreLocation
class ViewController: UIViewController ,CLLocationManagerDelegate{
// @IBOUTLET weak var map: MKMapView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// for use in foreground
if CLLocationManager.authorizationStatus() == .NotDetermined {
manager.requestWhenInUseAuthorization()
}
}
func locationManager (manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .Authorized || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
var locValue: CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.latitude) \(locValue.longitude)")
}
3 Answers
Michael Hulet
47,913 PointsAt the point where you're trying to print your location, the CLLocationManager hasn't had the chance to get it yet. However, said manager can tell you when it has a new location to give you. It does this with another delegate function, in which you should put your printing code, like this:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
manager.stopUpdatingLocation()
let currentLocation = locations.last as CLLocation
println("\(currentLocation.coordinate.latitude), \(currentLocation.coordinate.longitude)")
}
In order to receive these messages, you also need to make sure that the you're the delegate for the CLLocationManager object you set up. You'd do that like this:
//This goes in your viewDidLoad function
manager.delegate = self
Stephen Whitfield
16,771 PointsSo basically you have to make your view controller conform to the CLLocationManager protocol. You set your CLLocation manager, now set the delegate to self. You should be able to access the delegate methods from there.
Bradley Maskell
8,858 PointsHave you set your CLLocationManagerDelegate? Have you updated your info.plist file to NSLocationAlwaysUsageDescription?