Swift 地理定位

2019-06-06  本文已影响0人  独孤伊人_xie
import CoreLocation

@objcMembers class XHLocation: NSObject, CLLocationManagerDelegate {
   
   var locationManager : CLLocationManager!
   var locationBlock : passParameterBlock!
   
   class func sharedInstance() -> XHLocation {
       struct SharedStatic {
           static var instance: XHLocation = XHLocation()
       }
       return SharedStatic.instance
   }
   
   func initLacationManager(locationBlock:@escaping passParameterBlock) {
       if CLLocationManager.locationServicesEnabled() {
           locationManager = CLLocationManager.init()
           locationManager.delegate = self
           locationManager.requestAlwaysAuthorization()
           locationManager.requestWhenInUseAuthorization()
           locationManager.desiredAccuracy = kCLLocationAccuracyBest
           locationManager.distanceFilter = 5.0
       }
       locationManager.startUpdatingLocation()
       self.locationBlock = locationBlock
   }
   
   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
       
       let curLoc : CLLocation = locations.first!
       print("经度:" + String(curLoc.coordinate.longitude) + " 纬度:" + String(curLoc.coordinate.latitude))
       CLGeocoder.init().reverseGeocodeLocation(curLoc) {[weak self] (placemarks, error) in
           if error != nil {
               return
           }
           for placemark in placemarks! {
               let address : NSDictionary = placemark.addressDictionary! as NSDictionary
               if (!JSONSerialization.isValidJSONObject(address)) {
                   print("无法解析出JSONString")
                   return
               }
               let arr = address.object(forKey: "FormattedAddressLines") as! NSArray
               self?.locationBlock(arr[0] as? String)
           }
           self?.locationManager.stopUpdatingLocation()
       }
       
   }
   
   func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
       print(error)
   }
}
上一篇下一篇

猜你喜欢

热点阅读