I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView
). I want to find and update the location of the user (like in the Apple Map app).
I tried this, but nothing happened:
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()
}
}
}
Could you please help me?
You have to override CLLocationManager.didUpdateLocations
(part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
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)
}
}
NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
key in your Info.plist to get the location services to work.
Thanks for your answer Zisoft. But, to use the function, I have to "save" all my new locations in a kind of list ? Then, is
startUpdatingLocation()
suffisant to update the location ? NOTE: Euh... sorry but how can I do it please ? :s Thank you very much !After you have called
startUpdatingLocation
once,didUpdateLocations
is fired everytime a location change is detected. You can do whatever you need with the location, i.e. store it in an array to draw a path on the map view.ok thanks. And how can I include the
NSLocationAlwaysUsageDescription
key in my Info.plist please ?In XCode, click on Info.plist and add a new row. Use
NSLocationAlwaysUsageDescription
as the key and the text you want to present to the user as value (String).Ok Thank you ! And no value ?