The SUSI Server responds with intelligent answers to the user’s queries. To make these answers better, the server makes use of the user’s location which is sent as a parameter to the query request each time. To implement this feature in the SUSI iOS client, we use the CoreLocation framework provided by Apple which helps us to get the user’s location coordinates and add them as a parameter to each request made.
In order to start with using the CoreLocation framework, we first import it inside the view controller.
import CoreLocation
Now, we create a variable of type CLLocationManager which will help us to use the actual functionality.
// Location Manager var locationManager = CLLocationManager()
The location manager has some delegate methods which give an option to get the maximum accuracy for a user’s location. To set that, we need the controller to conform to the CLLocationManagerDelegate, so we create an extension of the view controller conforming to this.
extension MainViewController: CLLocationManagerDelegate { // use functionality }
Next, we set the manager delegate.
locationManager.delegate = self
And create a method to ask for using the user’s location and set the delegate properties.
func configureLocationManager() { locationManager.delegate = self if CLLocationManager.authorizationStatus() == .notDetermined || CLLocationManager.authorizationStatus() == .denied { self.locationManager.requestWhenInUseAuthorization() } locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBest }
Here, we ask for the user location if it was previously denied or is not yet determined and following that, we set the `distanceFilter` as kCLDistanceFilterNone and `desiredAccuray` as kCLLocationAccuracyBest.. Finally, we are left with starting to update the location which we do by:
locationManager.startUpdatingLocation()
We call this method inside viewDidLoad to start updation of the location when the view first loads. The complete extension looks like below:
extension MainViewController: CLLocationManagerDelegate { // Configures Location Manager func configureLocationManager() { locationManager.delegate = self if CLLocationManager.authorizationStatus() == .notDetermined || CLLocationManager.authorizationStatus() == .denied { self.locationManager.requestWhenInUseAuthorization() } locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } }
Now, it’s very easy to use the location manager and get the coordinates and add it to the params for each request.
if let location = locationManager.location { params[Client.ChatKeys.Latitude] = location.coordinate.latitude as AnyObject params[Client.ChatKeys.Longitude] = location.coordinate.longitude as AnyObject }
Now the params which is a dictionary object is added to each request made so that the user get’s the most accurate results for each query he makes.
References: