【问题标题】:Obtaining iPhone Latitude & Longitude获取 iPhone 纬度和经度
【发布时间】:2015-03-02 01:19:19
【问题描述】:

我一直在尝试检索 iPhone 的纬度和经度,以便将其传递给外部函数以进行地理标记。然而,我一直很不成功。这是我现在正在使用的代码。

let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func findMyLocation (sender:AnyObject)
{
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

        if error == nil
        {
            println("Reverse geocoder failed with error " + error.localizedDescription)
            return
        }

        if placemarks.count > 0
        {
            let pm = placemarks[0] as CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            println("Problem with the data received from geocoder")
        }
    })
}

func displayLocationInfo(placemark: CLPlacemark) {
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()
    if (placemark.postalCode != nil)
    {
        println(placemark.postalCode)
        println("just tried to print placemark's postal code")
    }
        //println(placemark.locality ? placemark.locality : "")
        //println(placemark.postalCode ? placemark.postalCode : "")
        //println(placemark.administrativeArea ? placemark.administrativeArea : "")
        //println(placemark.country ? placemark.country : "")
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("Error while updating location " + error.localizedDescription)
}

到目前为止,当我运行该程序时,我几乎一无所获。我有一个小按钮,上面写着“找到我”,单击后,输出框中没有弹出任何内容。我将 iOS 模拟器的调试位置设置为“Apple”,并且我之前尝试过在尝试运行程序时始终在模拟器的设置中启用位置服务(尽管目前它没有显示我的应用程序和这样做的选项)。 我真的只想得到一个经纬度的双倍值,如果有一个简单的东西那就太好了。

【问题讨论】:

    标签: ios iphone swift location


    【解决方案1】:
    1. 您应该只请求一种类型的授权。选择对您的应用的用户体验最有意义的一种。

    2. 您可能缺少您的目的字符串,现在需要它来激活位置服务。将以下键之一添加到您的 Info.plist:

      • NSLocationAlwaysUsageDescription - 如果请求 Always 权限
      • NSLocationWhenInUseUsageDescription - 如果请求 WhenInUse 权限

      键的值应该是一个字符串,说明您为什么需要位置权限。

    【讨论】:

    • 我对 XCode 很陌生 - 我究竟如何添加这些键之一?它长什么样子,去哪儿了?
    • 应该有一个叫supporting files的文件夹。其中有一个名为 target-Info.plist 的文件,其中 target 是项目应用程序目标的名称。您在该文件中添加键/值对。如果您是 Xcode 的新手,我建议您在寻求帮助之前阅读一些指南和教程以掌握它的窍门。不懂行话的人很难帮助。
    猜你喜欢
    • 2019-03-25
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多