CLLocation Manager in Swift to get Location of User
You are missing two things. First, you have to ask for permission using requestAlwaysAuthorization
or requestWhenInUseAuthorization()
. So your viewDidLoad()
should be like this:
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
Second, edit your Info.plist
as indicated here.
Not getting users current location in swift 4
The problem is your Info.plist. You need all three keys:
Fix that and the app will spring to life. I pasted your code into a project, set up the Info.plist as shown, and it worked fine.
You can actually omit "Always" starting in iOS 11, but you must have both "When In Use" and "Always and When In Use", even if you are planning to ask only for "Always".
The runtime was in fact telling you this all along in the Xcode console, but you apparently weren't looking at it. It says:
The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data.
How to get current longitude and latitude using CLLocationManager-Swift
IMHO, you are over complicating your code when the solution you are looking is pretty simple.
I have done it by using the following code:
First create an instance of CLLocationManager
and Request Authorization
var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
then check if the user allowed authorization.
var currentLocation: CLLocation!
if
CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways
{
currentLocation = locManager.location
}
to use it just do this
label1.text = "\(currentLocation.coordinate.longitude)"
label2.text = "\(currentLocation.coordinate.latitude)"
Your idea of setting them to the label.text
is correct, however the only reason I can think of is that the user is not giving you permission and that is why your current Location data will be nil.
However you would need to debug and tell us that.
Also the CLLocationManagerDelegate
is not necessary.
Hopefully this helps. Ask away if you have doubts.
How to fetch current location in appdelegate using swift
// Just call setupLocationManager() in didFinishLaunchingWithOption.
func setupLocationManager(){
locationManager = CLLocationManager()
locationManager?.delegate = self
self.locationManager?.requestAlwaysAuthorization()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.startUpdatingLocation()
}
// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if currentLocation == nil {
currentLocation = locations.last
locationManager?.stopMonitoringSignificantLocationChanges()
let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locationValue)")
locationManager?.stopUpdatingLocation()
}
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error")
}
Related Topics
Convert Nsdata to Sockaddr Struct in Swift
How to Render a Whole Uitableview as an Uiimage in iOS
How to Force Wkwebview to Ignore Hardware Silent Switch on iOS
How to Access Both Objective-C and Swift Classes from Same Storyboard
How to Create a User with Multiple Attributes in Firebase with Swift
Dynamic Link Object Has No Url
Button Action in Custom Uitableviewcell Affects Other Cells
Swift Image Retrieving from Parse Sdk - Getting Crashed
How to Change Uidatepicker to a Specific Time (In Code)
Make Segue Programmatically in Swift
How to Render a Uiview with Transparent Background on an Scnplane in Arkit
Move a Node to Finger Using Swift + Spritekit
Swift Get String Between 2 Strings in a String
Combine Framework Serialize Async Operations