How to get current longitude and latitude using CLLocationManager-Swift

后端 未结 6 501
囚心锁ツ
囚心锁ツ 2020-12-04 12:43

I want to get the current longitude and latitude of a location using Swift and display them via labels. I tried to do this but nothing displays on the labels.



        
6条回答
  •  攒了一身酷
    2020-12-04 13:06

    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.

提交回复
热议问题