我一直试图检索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”,并且我以前尝试过在尝试运行程序时始终在模拟器的设置中启用位置服务(尽管当前它没有显示我的应用程序和这样做的选项)。
我真的只想得到纬度和经度的双倍值,如果有一个简单的东西会很好。

最佳答案

您应该只请求一种类型的授权。选择对应用程序的用户体验最有意义的一个。
您可能缺少目的字符串,现在激活位置服务需要该字符串。将以下键之一添加到Info.plist:
NSLocationAlwaysUsageDescription-如果总是请求权限
NSLocationWhenInUseUsageDescription-如果请求WhenInUse权限
键的值应该是一个字符串,解释为什么需要位置权限。

10-08 06:25
查看更多