大多数情况下APP会在开启应用的时候获取当前的位置,所以我写在APPDelegate里
第一步
import CoreLocationvar locationManager = CLLocationManager()
第二步
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {//开启定位loadLocation() return true
}
第三步 实现代理方法
extension AppDelegate: CLLocationManagerDelegate
{//打开定位
func loadLocation()
{locationManager.delegate = self//定位方式locationManager.desiredAccuracy = kCLLocationAccuracyBest//iOS8.0以上才可以使用if(UIDevice.currentDevice().systemVersion >= "8.0"){//始终允许访问位置信息locationManager.requestAlwaysAuthorization()//使用应用程序期间允许访问位置数据locationManager.requestWhenInUseAuthorization()}//开启定位locationManager.startUpdatingLocation()
}//获取定位信息
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {//取得locations数组的最后一个let location:CLLocation = locations[locations.count-1]currLocation = locations.last!//判断是否为空if(location.horizontalAccuracy > 0){lat = Double(String(format: "%.1f", location.coordinate.latitude))long = Double(String(format: "%.1f", location.coordinate.longitude))print("纬度:\(long!)")print("经度:\(lat!)")LonLatToCity()//停止定位locationManager.stopUpdatingLocation()}}//出现错误
func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) {print(error)
}///将经纬度转换为城市名
func LonLatToCity() {let geocoder: CLGeocoder = CLGeocoder()geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void inif(error == nil){let array = placemark! as NSArraylet mark = array.firstObject as! CLPlacemark//城市var city: String = (mark.addressDictionary! as NSDictionary).valueForKey("City") as! String//国家let country: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("Country") as! NSString//国家编码let CountryCode: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("CountryCode") as! NSString//街道位置let FormattedAddressLines: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("FormattedAddressLines")?.firstObject as! NSString//具体位置let Name: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("Name") as! NSString//省var State: String = (mark.addressDictionary! as NSDictionary).valueForKey("State") as! String//区let SubLocality: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("SubLocality") as! NSString//如果需要去掉“市”和“省”字眼State = State.stringByReplacingOccurrencesOfString("省", withString: "")let citynameStr = city.stringByReplacingOccurrencesOfString("市", withString: "")}else{print(error)}}}}