Reputation: 150
I'm really new to swift and am trying to figure out why I am getting a nil value when running this program. I have tried adding a func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!)
but that didn't seem to work. Any help would be greatly appreciated. Thanks
Here is the code (PS: This is the value of the variable locManager: var locManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.systemGreen
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
locManager.requestWhenInUseAuthorization()
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
let locationZoom = locations.last as! CLLocation
}
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways
{
currentLocation = locManager.location
//getting locations
let longa = currentLocation.coordinate.longitude ***<- (Error occurring at this line)***
let latta = currentLocation.coordinate.latitude
nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
print("name 1 is ", name)
}
nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
print("name 2 is ", name)
}
}
}
Upvotes: 0
Views: 220
Reputation: 285072
There are two major issues:
The method didUpdateLocations
must be declared on the top level of the class (same level as viewDidLoad
) and all the code to process the location must be inside this method
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
guard let currentLocation = locations.last else { return }
//getting locations
let longa = currentLocation.coordinate.longitude
let latta = currentLocation.coordinate.latitude
nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
print("name 1 is ", name)
}
nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
print("name 2 is ", name)
}
}
self
and call startUpdatingLocation()
Upvotes: 1
Reputation: 52538
Probably currentLocation = nil. Use
if let currentLocation = locManager.location {
// Code for currentLocation != nil
} else {
// Code for currentLocation == nil
}
or something similar.
Upvotes: 1