有人可以帮我理解为什么在下面的代码中会有这样的输出:
[1 + 37.49638550,-122.31160280> +/- 5.00米(速度32.65 mps /航向 294.26)@ 7/27 / 16,4:34:19 AM东部夏令时间]
n / a Belmont Belmont
Belmont 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)
答案 0 :(得分:1)
这不是范围问题,而是时间问题。你得到n / a,因为在执行print语句时闭包还没有运行。
其他变量保留先前调用的值。