【发布时间】:2023-03-22 08:39:01
【问题描述】:
我正在尝试使用 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()
在下一行之后,应用程序崩溃并且我收到错误:致命错误:在展开 Optional 值时意外发现 nil。我认为这意味着 ourLocation 从未真正设置过。 (请注意,我正在转换为浮动,因为我需要将位置作为浮动存储在我的服务器上)
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 文件!在模拟器中开启了定位功能。
【问题讨论】:
-
testClass 的 lat 属性是浮点数吗?
-
是的 var lat: Float = 0.0
-
对不起,名字混淆了 testClass 实际上是类 item :/brainfart 的一个实例。不应该影响结果
标签: ios swift core-location