我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。为此,我想用地图(MKMapView)做一个简单的视图。我想查找并更新用户的位置(例如在Apple Map应用程序中)。
MKMapView
我试过了,但是什么也没发生:
import MapKit import CoreLocation class MapView : UIViewController, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } }
请你帮助我好吗?
您必须重写CLLocationManager.didUpdateLocations(CLLocationManagerDelegate的一部分)才能在位置管理器检索当前位置时得到通知:
CLLocationManager.didUpdateLocations
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last{ let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.map.setRegion(region, animated: true) } }
注意:如果目标是iOS 8或更高版本,则必须在Info.plist中包括NSLocationAlwaysUsageDescription或NSLocationWhenInUseUsageDescription键,才能使定位服务正常工作。
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription