swift地图定位(八)获取当前城市名称(定位+反地理编码)

时间:2021-11-09 20:31:38
import UIKit
import CoreLocation

class ViewController: UIViewController {
    lazy var locationM: CLLocationManager = {//info.plist add :Privacy - Location Always Usage Description
        let locationM = CLLocationManager()
        locationM.delegate = self
        if #available(iOS 8.0, *) {
            locationM.requestAlwaysAuthorization()
        }
        return locationM
    }()
    
    lazy var geoCoder: CLGeocoder = {
        return CLGeocoder()
    }()
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        locationM.startUpdatingLocation()
    }
}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let newLocation = locations.last else {return}
        print(newLocation)//<+31.26514482,+121.61259089> +/- 50.00m (speed 0.00 mps / course -1.00) @ 2016/11/14 中国标准时间 14:49:51
        if newLocation.horizontalAccuracy < 0 { return }
        geoCoder.reverseGeocodeLocation(newLocation) { (pls: [CLPlacemark]?, error: Error?) in
            if error == nil {
                guard let pl = pls?.first else {return}
                print(pl.name!)//金京路
                print(pl.locality!)//上海市
                /*
                open var name: String? { get } // eg. Apple Inc.
                open var thoroughfare: String? { get } // street name, eg. Infinite Loop
                open var subThoroughfare: String? { get } // eg. 1
                open var locality: String? { get } // city, eg. Cupertino
                open var subLocality: String? { get } // neighborhood, common name, eg. Mission District
                open var administrativeArea: String? { get } // state, eg. CA
                open var subAdministrativeArea: String? { get } // county, eg. Santa Clara
                open var postalCode: String? { get } // zip code, eg. 95014
                open var isoCountryCode: String? { get } // eg. US
                open var country: String? { get } // eg. United States
                open var inlandWater: String? { get } // eg. Lake Tahoe
                open var ocean: String? { get } // eg. Pacific Ocean
                open var areasOfInterest: [String]? { get } // eg. Golden Gate Park
                */
            }
        }
        manager.stopUpdatingLocation()
    }
}