Using CLLocationManager protocol you are able to track user on his IPhone.
- First things first.
Add MapView to Main.storyboard an then create instance of it in ViewController
Choosing YourProject.xcodeproject Go to Build Phases then choose Link Binary With Libraries
and add framework, which display info for user to allow acces to track.
Using + add CoreLocation.framework to library of your project.
- Go to
info.plistchoosing it from main menu of your project and add two rules: key-value. Right click, andadd row.
First Key:
NSLocationWhileInUseUsageDescription
as type String and value add sentence which will display to the user while fired aplication up.
f.e: "I need to know your location"
Second Key:
NSLocationAlwaysUsageDescription as String type and value: "Add your info here".
-
Import
CoreLocationthen add protocolCLLocationManagreDelagateto yourViewController -
Add variable which holds userlocation:
var locationManager = CLLocationManager() -
Add
locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest -
Add properties to
locationManagerwhich could track user. ` locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() -
Add method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print(locations) }
- Fire up an aplication. In console / debugging area You can see longitude and latitude of your location.
Go to Simulator -> Features and choose: City Run, City Bike, FreeWayDrive
- In function
locationManagercreate variable which stores Users position.
let userLocation: CLLocation = locations[0]
- Then we need longitude and latitude which holds user position.
let latitide = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
-
Import Map Kit and add
MKMapViewDelegateprotocol toViewController -
Add MapCoortinates to
ViewControllerwhich dipslay user location on Map.
` let latDelta: CLLocationDegrees = 0.05 let longDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)
let location = CLLocationCoordinate2D(latitude: latitide, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
`