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.
Swift get Coordinates Latitude Longitude in a Variable
First you need to import CoreLocation:
import CoreLocation
// and add CLLocationManagerDelegate to the class declaration
Then you need to declare the location manager and variables to hold the lat and long values:
// set these outside of any functions in your class
let locationManager = CLLocationManager() // create Location Manager object
var latitude : Double?
var longitude : Double?
After that is done you want to ask for authorization to use the location of the device. You will need to add the proper items ( NSLocationAlwaysUsageDescription
, and/or NSLocationWhenInUseDescription
I beleive) to your .plist file to do so.
// in the function you want to grab the user's location from
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
// You will need to update your .plist file to request the authorization
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
Then you'll need to add the function to retrieve the location
// Add this function to your program
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
// set the value of lat and long
latitude = location.latitude
longitude = location.longitude
}
After all of that you will be able to use the latitude and longitude variables whenever you want to. You will also want to tell the locationManager
to stop updating the location after you get what you want like, locationManager.stopUpdatingLocation()
.
You can create the string like:
// in the function where you need the postString you can do this
var postString = ""
if let lat = latitude, let long = longitude {
locationManager.stopUpdatingLocation()
postString = "latiTude=\(lat)&longiTude=\(long)"
// do task here now that postString is not empty
}
How to get latitude and longitude of a user's location in iOS
Code updated for Swift 3.x and Swift 4.x
As I can see you have used print(placemark.location)
in your code.
So if you want to get only latitude use this code
print(placemark.location.coordinate.latitude)
and if you want to get only longitude use this code
print(placemark.location.coordinate.longitude)
Hope this helps !
Find city name and country from latitude and longitude in Swift
I would recommend integrating Google Maps API with your project. If you do, your task can be achieved using Reverse Geocoding Google provides.
Furthermore, Google there is Google Maps SDK for IOS development, which is also worth considering.
UPD: You can do that without integrating maps into your project. Basing on this answer, you can achieve that using http requests to Google API. The request to:
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=API_KEY
would return JSON
object with information about the requested place, including country and city name.
BTW, I highly recommend using Alamofire to make http requests in Swift.
Related Topics
Uipopovercontroller Dealloc Reached While Popover Is Still Visible
How to Keep an Iphone/iPad Web App in Full Screen Mode
How to Calculate the Height of an Nsattributedstring with Given Width in iOS 6
Swiftui: Unwanted Split View on iPad
Determine Mime Type from Nsdata
How to Cache Videos? iOS - Swift
Loading a Resource (E.G. Storyboard) in a Swift Framework
iPhone Uitextfield Background Color
How to Check Whether iPhone and Apple Watch Are Connected
Can a Standard Accessory View Be in a Different Position Within a Uitableviewcell
How to Create a Release Build in Xcode
How to Hide/Show Tabbar When Tapped Using Swift in iOS8
How to Add Textfield in Uialertcontroller
Ios: Determine If Device Language Is Right to Left (Rtl)
Wanted: How to Reliably, Consistently Select an Mkmapview Annotation
Modifying Ekparticipants (Attendees) in Eventkit Like Sunrise