This tutorial shows you how to get your current location (latitude and longitude) in Swift 4.2. Please note, for all iPAD users you will need a Cellular iPAD which comes with inbuilt GPS. Also, you will be able to use GPS while you have wifi and 3G/4G/5G turned off. You can find the source code at the end of the tutorial.
What does this app do?
– It will prompt you with permission to request access you location
– Your latitude and longitude coordinates will update every few seconds.
Language: Swift 4.2
Software: Xcode
Software: Xcode
CODE:
View Controller
import UIKit
import MessageUI
import CoreLocation
class ViewController: UIViewController, MFMailComposeViewControllerDelegate, CLLocationManagerDelegate {
@IBOutlet weak var lat: UITextField!
@IBOutlet weak var long: UITextField!
// Used to start getting the users location
let locationManager = CLLocationManager()
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
// For use when the app is open
locationManager.requestWhenInUseAuthorization()
// If location services is enabled get the users location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest // You can change the locaiton accuary here.
locationManager.startUpdatingLocation()
var latitude: Double? {
if let text = lat.text {
return Double(text)
} else {
return nil
}
}
var longitude: Double? {
if let text = long.text {
return Double(text)
} else {
return nil
}
}
timer.invalidate() // just in case you had existing `Timer`, `invalidate` it before we lose our reference to it
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
}
}
// Print out the location to the console
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
//print(location.coordinate.latitude)
self.lat.text = "\(location.coordinate.latitude)"
self.long.text = "\(location.coordinate.longitude)"
}
}
// If we have been deined access give the user the option to change it
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if(status == CLAuthorizationStatus.denied) {
showLocationDisabledPopUp()
}
}
// Show the popup to the user if we have been denied access
func showLocationDisabledPopUp() {
let alertController = UIAlertController(title: "Background Location Access Disabled",
message: "In order to submit offline report you need to enable your location services.",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
let openAction = UIAlertAction(title: "Open Settings", style: .default) { (action) in
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
}
alertController.addAction(openAction)
self.present(alertController, animated: true, completion: nil)
}
func grabit() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation();
print(self.lat.text ?? 0)
print(self.long.text ?? 0)
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
Screenshots:

Source code: