获得iPhone Latitude&经度

时间:2015-03-02 01:19:19

标签: ios iphone swift location

我一直在尝试检索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”,我以前尝试在尝试运行程序时始终在模拟器的设置中启用位置服务(尽管目前它没有显示我的应用程序和选项)。 我真的只想获得纬度和经度的双倍值,如果有一个简单的东西,那将是伟大的。

1 个答案:

答案 0 :(得分:0)

  1. 您只应申请一种授权。选择对您的应用的用户体验最有意义的那个。

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

    • NSLocationAlwaysUsageDescription - 如果请求始终允许
    • NSLocationWhenInUseUsageDescription - 如果请求WhenInUse权限

    密钥的值应该是一个字符串,用于解释您希望获得位置权限的原因。