我正在尝试使用 CoreLocation 获取 iOS 8 中的纬度和经度坐标。看了很多帖子后,我仍然不确定如何去做。另外,我希望对 locationManager() 方法进行简要说明,因为我不明白它们在获取位置方面扮演什么角色。我是否需要调用这些方法?因为我从未在任何示例中看到它们被调用。
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()
在下一行之后,应用程序崩溃,我收到错误: fatal error :在展开可选值时意外发现 nil。我认为这意味着 ourLocation 永远不会真正设置。 (请注意,我正在转换为 float ,因为我需要将位置作为 float 存储在我的服务器上)
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()
}
}
请注意,我已经适本地更新了我的 plist 文件!位置在模拟器中打开。
最佳答案
检查你传递给变量的值是否为 nil
if ourLocation.coordinate.latitude != nil
{
testClass.lat = Float(ourLocation.coordinate.latitude)
println(testClass.lat)
}
同时检查经度。
关于ios - Swift CoreLocation获取经纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018562/