裏面我ViewController's
類viewDidLoad
方法,我有:MKMapItem.forCurrentLocation()返回 「未知位置」
override func viewDidLoad() {
super.viewDidLoad()
requestAuthorization()
locationManager.delegate = self
print(MKMapItem.forCurrentLocation())
}
這裏是requestAuthorization()
功能:
private func requestAuthorization(){
if CLLocationManager.authorizationStatus() == .notDetermined{
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
else if CLLocationManager.authorizationStatus() == .denied{
//TODO
}
}
問題是,forCurrentLocation()
函數永遠不會返回實際的用戶位置返回MKMapItem的座標是:(緯度:0,經度:0)。這是打印功能的結果。
MKMapItem:0x60000014e020 isCurrentLocation = 1; name =「未知位置」;
我在做什麼錯?
編輯:
我想用MKMapItem.forCurrentLocation()
是,我打算讓用戶在prepareForSegue
座標的原因。我認爲這比使用didUpdateLocations
委託方法更容易。看到代碼:
if segue.identifier == "categories",
let destinationVC = segue.destination as? CategoriesGroupViewController{
if let cell = sender as? UICollectionViewCell{
let indexPath = categoriesCollectionView.indexPath(for: cell)
destinationVC.groupOfDestinations = destinationsByCategory[indexPath!.row]
// 0 is index for Near Me cell
if indexPath?.row == 0 {
destinationVC.groupOfDestinations = getNearMeDestinations()
}
}
private func getNearMeDestinations() -> GroupOfDestinations{
let userCoordinates = MKMapItem.forCurrentLocation().placemark.coordinate
let nearMeCircularRegion: CLCircularRegion = CLCircularRegion(center: userCoordinates, radius: 10000, identifier: "nearMe")
...
return nearMeDestinations
}
如果您在ViewController中有MKMapView,請使用print(mapView.userLocation.location?.coordinate)。 –