可有人请帮助我理解为什么在下面的代码将有一个像这样的输出:迅速变量范围
[< + 37.49638550,-122.31160280> +/-5.00米(速度32.65 MPS /当然 294.26)@ 16年7月27日,上午04时34分19秒东部时间]
N/A贝尔蒙特贝尔蒙特
贝尔蒙特1
也就是说,为什么变量locality
的值为“n/a”而在特定点打印,而localityVC
& localityGlobal
永远不会?这是纯粹的范围问题还是与CLGeocoder()
有关?由于
import UIKit
import MapKit
import CoreLocation
var localityGlobal: String = "n/a"
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var localityVC: String = "n/a"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("hello")
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation: CLLocation = locations[0]
var locality: String = "n/a"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("CLGeocoder.reverseGeocodeLocation() failed")
return
}
if placemarks!.count > 0 {
locality = placemarks![0].locality!
self.localityVC = placemarks![0].locality!
localityGlobal = placemarks![0].locality!
print(locality, placemarks!.count)
} else {
print("CLGeocoder.reverseGeocodeLocation() error in geocoder data")
}
})
print(locality, localityVC, localityGlobal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
为了在上面运行,你还需要有:
Build Phases -> Link Binary with Libraries
包括CoreLocation.framework
,Info.plist
必须有变量NSLocationWhenInUseUsageDescription
和NSLocationAlwaysUsageDescription
集,Simulator -> Debug -> Location
设置为类似Apple
,City Bicycle Ride
,City Run
或Freeway Drive
我跑的Xcode 7.3.1(7D1014)
'reverseGeocodeLocation'异步工作。完成处理程序总是在'didUpdateLocations'委托方法末尾的'print'行之后调用**。 – vadian
这是我的第一个猜测,但是localityVC和localityGlobal也应该打印“n/a”,不是? – rockhammer