Swift + CLLocationManager:如何判断用户是否在特定的城市?

我使用CLLocationManager来请求用户的位置。 但是,如果他们在纽约市之外,我想默认到某个坐标。 有没有办法检查他们是否在某个城市?

import UIKit import CoreLocation import GoogleMaps private let kDefaultLatitude: Double = 40.713 private let kDefaultLongitude: Double = -74.000 private let kDefaultZoomLevel: Float = 16.0 class RootMapViewController: UIViewController { @IBOutlet weak var mapView: GMSMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() fetchLocation() } private func fetchLocation() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } } // MARK: CLLocationManagerDelegate extension RootMapViewController: CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { locationManager.stopUpdatingLocation() let userCoordinates = locations[0].coordinate // How do I check if the user is in NYC? // if user is in nyc centerMapOn(userCoordinates) mapView.myLocationEnabled = true mapView.settings.myLocationButton = true // else default to Times Square } } 

您可以使用反向地理编码。 例如,你可以放置:

 geocoder:CLGeocoder = CLGeocoder() geocoder.reverseGeocodeLocation(locations[0],completionHandler{ if error == nil && placemarks.count > 0 { let location = placemarks[0] as CLPlacemark print(location.locality) }) 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])