Introduction to the post get user location in swift4 using CLLocationManager
In this tutorial, we will learn how to get user current location in swift 4. For getting user current location, we will use Corelocation framework for location updates and Mapkit framework in order to show user current position on map(using default map i.e Apple map) . This tutorials is written in swift4. So let us dive in to the tutorial and learn how to get user current location in swift4 using CoreLocation framework.
Step 1: Create a new project using “Single view app” template and name it “UserLocationAndMapkit”.
Step 2: Open “Main.storyboard” and on your ViewController’s view drag “Map Kit View” i.e. MKMapView.
Step 3: Open “ViewController.swift” and create IBOutlet for “MKMapView”. Also import “MapKit” framework.
Step 4: Open “Main.storyboard” and connect mapView IBOutlet to the map aka MKMapView placed on ViewController’s view.
Step 5: Open “ViewController.swift”. First import CoreLocation framework so that we can use classes to detect user current location. Below is the code that we detect user current location, we will explain the code after you went through it.
In the above code, we created instance of CLLocationManager and named it locationManager. Inside viewDidLoad function, first we set MKMapView, “showsUserLocation” property to true. This will display blue dot as current location on mapView. Then we detect if location services are enabled for the device on which our app is running, if not then control will move’s to else block where we print a message you can show alert to user for better user experience.
If locationServicesEnabled return true then we detect if user authorized our app to use location services or not, If authorization status comes as “denied”, “restricted”, “notDetermined”, then we will again ask user for authorization for location. Here we requested user to allow our app to access location when app in use only (requestWhenInUseAuthorization), you can also choose “requestAlwaysAuthorization”, this permission will detect user location always in background mode too . Lastly we set location desired accuracy to best and delegate to self so that we get notified about user location update or failed, then finally we start monitoring for location updates by calling the method “startUpdatingLocation”.
Once user location is detected, then “didUpdateLocations” delegate of CLLocationManager will be gets called, providing us latitude and longitude. If it failed to get user current location then “didFailWithError” method will be invoked. In “didUpdateLocations” method, first we stop the location manger as we need only location for first time. The we create “MKCoordinateRegion” for our mapView, so that we can zoom our map to user current location.
Where to go from here;
In this tutorial, we learned how to get user current location and display it on MKMapView in swift4 language. You can download the source code from https://goo.gl/ES48XE