SwiftUI-从用户位置获取城市/位置信息

时间:2020-07-02 19:48:40

标签: swiftui core-location

我目前能够确定用户的经度/纬度并访问坐标。我该如何对坐标进行反向地理编码以确定用户当前所在的城市,以便可以显示该城市?

这是我当前的LocationManager文件

import Foundation
import MapKit

class LocationManager: NSObject, ObservableObject {

private let locationManager = CLLocationManager()
@Published var location: CLLocation? = nil

override init() {
    super.init()
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = kCLDistanceFilterNone
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
    }
}


class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.delegate = self
}

// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("notDetermined")
        manager.requestWhenInUseAuthorization()
    default:
        break
        }
    }
}

extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    guard let location = locations.last else {
        return
    }
    
    self.location = location
}


}

我想将城市信息传递到我的一个视图中,并在文本元素中输出城市。即“探索奥兰多”

1 个答案:

答案 0 :(得分:0)

您可以为此使用CLGeocoder

// Add below code to get address for touch coordinates.
        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: YOUR_LATITUDE, longitude: YOUR_LONGITUDE)
        geoCoder.reverseGeocodeLocation(location, completionHandler:
            {
                placemarks, error -> Void in

                // Place details
                guard let placeMark = placemarks?.first else { return }

                // Location name
                if let locationName = placeMark.location {
                    print(locationName)
                }
                // Street address
                if let street = placeMark.thoroughfare {
                    print(street)
                }
                // City
                if let city = placeMark.subAdministrativeArea {
                    print(city)
                }
                // Zip code
                if let zip = placeMark.isoCountryCode {
                    print(zip)
                }
                // Country
                if let country = placeMark.country {
                    print(country)
                }
        })

贷记Convert coordinates to City name?