swift 3 --- 定位和获取地理位置
-
首先在plist文件中添加Privacy - Location When In Use Usage Description ,后边填写展示的信息
The following app need to access to the user location to help the user to find the nearest wifi around
-
创建一个nsboject类
import CoreLocation class LocationManager: NSObject { static let shareInstance = LocationManager() let locationManager: CLLocationManager static let sharedInstance: LocationManager = { let instance = LocationManager() return instance }() override init() { self.locationManager = CLLocationManager() self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation //使用应用程序期间允许访问位置数据 locationManager.requestWhenInUseAuthorization() // 设置iOS设备是否可暂停定位来节省电池的电量。如果该属性设为“YES”,则当iOS设备不再需要定位数据时,iOS设备可以自动暂停定位。 self.locationManager.pausesLocationUpdatesAutomatically = true super.init() self.locationManager.delegate = self //开启定位 self.startUpdatingLocation() }
func startUpdatingLocation() {
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
} else {
//tell view controllers to show an alert
self.showTurnOnLocationServiceAlert()
}
}func showTurnOnLocationServiceAlert() { NotificationCenter.default.post(name: Notification.Name(rawValue:"showTurnOnLocationServiceAlert"), object: nil)
// NotificationCenter.default.addObserver(self, selector: #selector(self.showTurnOnLocationServiceAlert(_:)), name: Notification.Name(rawValue:"showTurnOnLocationServiceAlert"), object: nil)
}//MARK - selector Methods
func showTurnOnLocationServiceAlert(_ notification: NSNotification){
let alert = UIAlertController(title: "Turn on Location Service", message: "To use location tracking feature of the app, please turn on the location service from the Settings app.", preferredStyle: .alert)let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) if let url = settingsUrl { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) alert.addAction(settingsAction) alert.addAction(cancelAction)
//self.present(alert, animated: true, completion: nil)
}
}extension LocationManager:CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("hello")
if let newLoca = locations.last {
CLGeocoder().reverseGeocodeLocation(newLoca, completionHandler: { (pms, err) -> Void in
if let newCoordinate = pms?.last?.location?.coordinate {
manager.stopUpdatingLocation()//停止定位,节省电量,只获取一次定位
let currentCoordinate = newCoordinate//记录定位点经纬度
print("\(currentCoordinate.latitude)")
//取得最后一个地标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址
let placemark:CLPlacemark = (pms?.last)!
let location = placemark.location;//位置
let region = placemark.region;//区域
let addressDic = placemark.addressDictionary;//详细地址信息字典,包含以下部分信息
// let name=placemark.name;//地名
// let thoroughfare=placemark.thoroughfare;//街道
// let subThoroughfare=placemark.subThoroughfare; //街道相关信息,例如门牌等
// let locality=placemark.locality; // 城市
// let subLocality=placemark.subLocality; // 城市相关信息,例如标志性建筑
// let administrativeArea=placemark.administrativeArea; // 州
// let subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息
// let postalCode=placemark.postalCode; //邮编
// let ISOcountryCode=placemark.ISOcountryCode; //国家编码
// let country=placemark.country; //国家
// let inlandWater=placemark.inlandWater; //水源、湖泊
// let ocean=placemark.ocean; // 海洋
// let areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标
print(location ?? 1111,region ?? 1111,addressDic ?? 111)
}
})
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if (error as NSError).domain == kCLErrorDomain && (error as NSError).code == CLError.Code.denied.rawValue {
//User denied your app access to location information.
showTurnOnLocationServiceAlert()
}
}
}