Подтвердить что ты не робот

Как получить текущую долготу и широту с помощью CLLocationManager-Swift

Я хочу получить текущую долготу и широту местоположения с помощью Swift и отобразить их с помощью меток. Я попытался сделать это, но на ярлыках ничего не отображается.

import UIKit
    import CoreLocation
    class ViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet weak var longitude: UILabel!
    @IBOutlet weak var latitude: UILabel!
    let locationManager = CLLocationManager()
    override func viewDidLoad() {
            super.viewDidLoad()
            if (CLLocationManager.locationServicesEnabled()) {
                        locationManager.delegate = self
                        locationManager.desiredAccuracy = kCLLocationAccuracyBest
                        locationManager.requestWhenInUseAuthorization()
                        locationManager.startUpdatingLocation()
                    } else {
                        println("Location services are not enabled");
                    }
                }
        // MARK: - CoreLocation Delegate Methods
            func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
                locationManager.stopUpdatingLocation()
                removeLoadingView()
                if ((error) != nil) {
                    print(error)
                }
            }

            func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
                var locationArray = locations as NSArray
                var locationObj = locationArray.lastObject as CLLocation
                var coord = locationObj.coordinate
                longitude.text = coord.longitude
                latitude.text = coord.latitude
                longitude.text = "\(coord.longitude)"
               latitude.text = "\(coord.latitude)"
            }
    }
4b9b3361

Ответ 1

ИМХО, вы больше усложняете свой код, когда решение, которое вы ищете, довольно просто.

Я сделал это, используя следующий код:

Сначала создайте экземпляр CLLocationManager и авторизацию запроса

    var locManager = CLLocationManager()
    locManager.requestWhenInUseAuthorization()

затем проверьте, разрешено ли пользователю авторизацию.

var currentLocation: CLLocation!

if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){

      currentLocation = locManager.location

}

чтобы использовать его, просто сделайте это

label1.text = "\(currentLocation.coordinate.longitude)"
label2.text = "\(currentLocation.coordinate.latitude)"

Ваша идея установить их в label.text верна, однако единственная причина, по которой я могу думать, это то, что пользователь не дает вам разрешения, и поэтому ваши текущие данные местоположения будут нулевыми.

Однако вам нужно отлаживать и сообщать нам об этом. Также не требуется CLLocationManagerDelegate.

Надеюсь, это поможет. Спросите, есть ли у вас сомнения.

Ответ 2

Для Swift 3:

Сначала вам нужно установить разрешение на прием GPS-пользователей в info.plist.

введите описание изображения здесь

Установите: NSLocationWhenInUseUsageDescription со случайной строкой. И/или: NSLocationAlwaysUsageDescription со случайной строкой.

Тогда:

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

Готово.

Ответ 3

Несмотря на другие советы, вы должны использовать CLLocationManagerDelegate для безопасного извлечения местоположения (без его использования вы можете получить пустые места, когда менеджеру местоположения не хватает времени для обновления). Я настоятельно рекомендую обернуть код менеджера местоположений в статическом общедоступном помощнике (что-то вроде этих строк):

class Locator: NSObject, CLLocationManagerDelegate {
    enum Result <T> {
      case .Success(T)
      case .Failure(ErrorType)
    }

    static let shared: Locator = Locator()

    typealias Callback = (Result <Locator>) -> Void

    var requests: Array <Callback> = Array <Callback>()

    var location: CLLocation? { return sharedLocationManager.location  }

    lazy var sharedLocationManager: CLLocationManager = {
        let newLocationmanager = CLLocationManager()
        newLocationmanager.delegate = self
        // ...
        return newLocationmanager
    }()

    // MARK: - Authorization

    class func authorize() { shared.authorize() }
    func authorize() { sharedLocationManager.requestWhenInUseAuthorization() }

    // MARK: - Helpers

    func locate(callback: Callback) {
        self.requests.append(callback)
        sharedLocationManager.startUpdatingLocation()
    }

    func reset() {
        self.requests = Array <Callback>()
        sharedLocationManager.stopUpdatingLocation()
    }

    // MARK: - Delegate

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        for request in self.requests { request(.Failure(error)) }
        self.reset()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: Array <CLLocation>) {
        for request in self.requests { request(.Success(self)) }
        self.reset()
    }

}

Затем в поле зрения загрузилась (или где-либо еще, чтобы получить текущее местоположение):

Locator.shared.locate { result in
  switch result {
  case .Success(locator):
    if let location = locator.location { /* ... */ }
  case .Failure(error):
    /* ... */
  }
}

Ответ 4

В Swift

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    //Labels outlets

    @IBOutlet var localityTxtField: UITextField!
    @IBOutlet var postalCodeTxtField: UITextField!
    @IBOutlet var aAreaTxtField: UITextField!
    @IBOutlet var countryTxtField: UITextField!

    let locationManager = CLLocationManager()

    //View Didload

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

     //Button Location

    @IBAction func findMyLocation(_ sender: AnyObject) {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

            if (error != nil) {
                print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                return
            }

            if (placemarks?.count)! > 0 {

                print("placemarks",placemarks!)
                let pm = placemarks?[0]
                self.displayLocationInfo(pm)
            } else {
                print("Problem with the data received from geocoder")
            }
        })
    }

    func displayLocationInfo(_ placemark: CLPlacemark?) {
        if let containsPlacemark = placemark {

            print("your location is:-",containsPlacemark)
            //stop updating location to save battery life
            locationManager.stopUpdatingLocation()
            let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
            let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
            let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""

            localityTxtField.text = locality
            postalCodeTxtField.text = postalCode
            aAreaTxtField.text = administrativeArea
            countryTxtField.text = country
        }

    }


    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
          print("Error while updating location " + error.localizedDescription)
    }
}

Ответ 5

В текущей нити решение было предложено без делегата, но в Xcode 9.1 тестирование в симуляторе это не сработало, местоположение было нулевым. Этот код работал:

import UIKit импортировать MapKit

класс ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{

    let location = locations.last! as CLLocation

    /* you can use these values*/
    let lat = location.coordinate.latitude
    let long = location.coordinate.longitude
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}