美文网首页
Swift 地理定位

Swift 地理定位

作者: 独孤伊人_xie | 来源:发表于2019-06-06 09:43 被阅读0次
    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)
       }
    }
    

    相关文章

      网友评论

          本文标题:Swift 地理定位

          本文链接:https://www.haomeiwen.com/subject/ndibwftx.html