我正在尝试创建一个根据位置显示项目的应用。不幸的是我的代码仍在运行,并且不会等到我找到用户位置。它返回一个nil值。我怎么能避免这个?这是可能的,我怎样才能实现它。我的代码在
之下 override func viewDidLoad() {
super.viewDidLoad()
// check if locations eabled
print("I got here 1")
if CLLocationManager.locationServicesEnabled() {
self.locManager.delegate = self
self.locManager.desiredAccuracy = kCLLocationAccuracyBest
self.locManager.requestWhenInUseAuthorization()
self.locManager.startUpdatingLocation()
print("I got here 2")
}
else {
print ("Locations not enabled")
}
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to Refresh")
refresher.addTarget(self, action: "LoadItems", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
LoadItems()
}
我的LoadItems函数需要运行位置
答案 0 :(得分:1)
在您的代码中,您错过了locationManager.startUpdatingLocation()
。将其添加到CLLocationManager.locationServicesEnabled() if-statement
中,然后添加这两个功能
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Here you can call a function when you have a location
// And stop updating the location if you don´t need it anymore
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to find user´s location: \(error.localizedDescription)")
}
这样你就可以确保
了如果您想获得lat和long,请使用locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let location:CLLocationCoordinate2D = manager.location!.coordinate
lat = String(location.latitude)
long = String(location.longitude)