I am trying to use CoreLocation to get the latitude and longitude coordinates in iOS 8. After looking through a lot of posts, I am still unsure how to go about doing this. Also, I would appreciate a brief explanation of the locationManager() methods as I don't understand what role they play in obtaining the location. Do I ever need to call these methods? Because I never saw them called in any examples.
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationMan = CLLocationManager()
var ourLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationMan.delegate = self
self.locationMan.desiredAccuracy = kCLLocationAccuracyBest
self.locationMan.requestWhenInUseAuthorization()
self.locationMan.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations : [AnyObject]!){
locationMan.stopUpdatingLocation()
ourLocation = locations[0] as! CLLocation
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
@IBAction func button(sender: AnyObject) {
var testClass:item = item()
After the next line, the app crashes and I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value. I think this means that ourLocation never actually gets set. (Note that I am casting to float because I need to store the location as a float on my server)
testClass.lat = Float(ourLocation.coordinate.latitude)
println(testClass.lat)
testClass.long = Float(ourLocation.coordinate.longitude)
println(testClass.long)
testClass.name = "Nice"
testClass.description = "Wow this is pretty cool"
testClass.postItemToServer()
}
}
Note that I have updated my plist file appropriately! Location is turned on in the simulator.
Check if the values you are passing to variable are nil or not
Also check for longitude.