【发布时间】:2015-02-23 21:15:37
【问题描述】:
我正在使用 swift 为 IOS 实现用户定位。这是我的代码。
import UIKit
import CoreLocation
class localizationViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 500
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("Error: " + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Error with data")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
self.locationManager.stopUpdatingLocation()
var city = placemark.locality
var department = placemark.administrativeArea
var country = placemark.country
var latitude = placemark.location.coordinate.latitude
var longitude = placemark.location.coordinate.longitude
var date = placemark.location.timestamp
println(city)
println(department)
println(country)
println(latitude)
println(longitude)
println(date)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func actionLocation(sender: UISwitch) {
println("get location request")
}
}
我可以正确获取位置信息,但总是更新 3 或 4 次。我正在阅读,如果您设置 distanceFilter 这会停止,但是它对我不起作用。如何配置我的 didUpdateLocations 以使每个请求仅获取一个位置?我如何在动作元素中运行此功能(每个示例的开关或按钮)?最后一个问题,因为也许原因是,在第一个位置请求中,应用程序始终没有将 Accuary 的值作为距离过滤器......谢谢。
【问题讨论】: