可有人請幫助我理解爲什麼在下面的代碼將有一個像這樣的輸出:迅速變量範圍
[< + 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