How to check current longitude and latitude in Swift

In my first year as as IOS developer I got a lot of problems in developing the application, one of which was sending or post coordinate data to API. This example is simple to check that. This shows you how to get your current location (latitude and longitude) in Swift.

Get data longitude and latitude First you need to set allowance to receive User’s GPS in the info.plist.

Set: NSLocationWhenInUseUsageDescription with empty String. And set location always usege too: NSLocationAlwaysUsageDescription with the same empty String. If you source code and look like this.

<key>NSLocationAlwaysUsageDescription</key>
<string>App need location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App need location</string>

Put the code into your info.plist file, and then see this example code here :

import UIKit
import MapKit

class ViewController: UIViewController {

var locManager = CLLocationManager()
var currentLocation: CLLocation!

override func viewDidLoad() {
super.viewDidLoad()
locManager.requestWhenInUseAuthorization()

if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
currentLocation = locManager.location
print(currentLocation.coordinate.latitude)
print(currentLocation.coordinate.longitude)
}
}
}

After get the data now can post to API with the parameters.
Because it’s one of the many bugs I got during development. I made a website to log all bugs and how to fix them, this is my blog : https://scripttes.blogspot.com/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store