新手紧急求帮助,在viewDidLoad中得不到定位坐标和城市
下面代码中viewDidLoad里面
print("\(self.currentLocation)")
print("\(self.currentCity)")
结果始终是nil
locationManager里面
print("\(self.currentLocation)")
print("\(self.currentCity)")
结果是
Optional(<+31.00000000,+120.60000000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 5/14/17, 2:00:16 AM China Standard Time)
Optional("Suzhou")
怎么在viewDidLoad中取得坐标和城市
import UIKit
import CoreLocation
class WeatherCityVC: UIViewController,CLLocationManagerDelegate,URLSessionDelegate {
var locationManager:CLLocationManager!
var geocoder:CLGeocoder!
var currentLocation:CLLocation!
var currentCity:String!
func locate() {
if !CLLocationManager.locationServicesEnabled(){
print("定位失败")
return
}
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 500
locationManager.startUpdatingLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
locate()
print("\(self.currentLocation)")
print("\(self.currentCity)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - CoreLocation delegate
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
manager.stopUpdatingLocation()
self.currentLocation = locations.last
self.geocoder = CLGeocoder()
self.geocoder.reverseGeocodeLocation(self.currentLocation!, completionHandler:{(placeMarks,error) -> Void in
let pm = placeMarks
self.currentCity = pm?.first?.locality
print("\(self.currentLocation)")
print("\(self.currentCity)")
})
}
}