How to get current longitude and latitude using CLLocationManager-Swift

后端 未结 6 527
囚心锁ツ
囚心锁ツ 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

    For Swift 3:

    First you need to set allowance to receive User's GPS in the info.plist.

    Set: NSLocationWhenInUseUsageDescription with a random String. And/or: NSLocationAlwaysUsageDescription with a random String.

    Then:

    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){
                guard let currentLocation = locManager.location else {
                    return
                }
                print(currentLocation.coordinate.latitude)
                print(currentLocation.coordinate.longitude)
            }
        }
    }
    

    Done.

提交回复
热议问题