ios - Swift CoreLocation获取经纬度

标签 ios swift core-location

我正在尝试使用 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/

相关文章:

ios - AudioKit:长笛的无限播放时间和频移?

ios - "type of expression is ambiguous without more context"- 引用 appDelegate

iphone - 跨 View Controller 传输图像

ios - 使用 SwiftyJson 从锁匠那里提取值(value)

ios - 带有显示 null 标签的 uiswitchview View

ios - 在后台快速更新用户位置

iOS 强制地理定位以特定语言返回城市名称

iphone - 在 iPhone App 首次启动时显示信息 imageview

swift - 接受参数但不返回值的自动关闭

iphone - iPhone Simulator中的默认 map 应用无法确定位置