Latest Posts

Sorry, no posts matched your criteria.

Stay in Touch With Us

Odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore.


+32 458 623 874

302 2nd St
Brooklyn, NY 11215, USA
40.674386 – 73.984783

Follow us on social

The Gadget Book

How To Get User Location in Xcode Swift 4.0

In tutorial you will learn how to get user location in Xcode using swift.

We are going to start by creating a new Xcode Project, you can name this whatever you like but make sure the language is set to Swift.

New xCode project

We need to Configure the info.plist file, in order to get access to the devices GPS. We need to add permissions to the info.plist file that will prompt the user when the application is launched with a message asking for permission to use location services.

Add the “Privacy – Location When In Use Usage Description” and the “Privacy – Location Always and When In Use Usage Description” keys to the info.plist file with a message for the popup.

get user location info plist protocols

We then want to add a Map Object to our View Controller in the Storyboard and then right click to create  a outlet to the View Controller for the delegate. Jump over to the ViewController Swift file and import the MapKit model also create an IBOutlet for the outlet swift

We want to add the CLLocationManagerDelegate to the ViewController class to access the delegate. Create a global variable which represents the locationManager, just above the view did load method.

 var locationManager = CLLocationManager()

Next we need to add the following to the ViewDidLoad Method. This piece of code will show the popup which ask’s the user if the app can use the device’s location, if the location manager is enabled the delegate will be set and the location will start updating.

if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters

The didUpdateLocations method runs when the devices location has been changed or updated. We need to use this function to set the map after we get the user location.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
    let userLocation = locations.last
    let viewRegion = MKCoordinateRegionMakeWithDistance((userLocation?.coordinate)!, 600, 600), animated: true)

Hit Build and Run, a map view should load showing you the Current Location your simulator is set to. Check out our video Tutorial.

Source Code:

Post a Comment

You don't have permission to register