SBTLocation.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // SBTLocation.swift
  3. // SolarBT
  4. //
  5. // Created by weclouds on 2019/9/23.
  6. // Copyright © 2019 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. import CoreLocation
  10. class SBTLocation: NSObject,CLLocationManagerDelegate {
  11. var callback : ((String,String)->Void)?
  12. static let share = SBTLocation()
  13. var locationManager = CLLocationManager()
  14. override init() {
  15. super.init()
  16. }
  17. func startLocation() {
  18. log.debug("")
  19. locationManager.delegate = self
  20. locationManager.requestAlwaysAuthorization()
  21. locationManager.desiredAccuracy = kCLLocationAccuracyBest//定位最佳
  22. locationManager.distanceFilter = 500.0//更新距离
  23. locationManager.requestWhenInUseAuthorization()
  24. if (CLLocationManager.locationServicesEnabled()){
  25. locationManager.startUpdatingLocation()
  26. print("定位开始")
  27. }
  28. }
  29. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  30. //取得Locations数组的最后一个
  31. // log.debug
  32. let location:CLLocation = locations.last ?? CLLocation()
  33. //判断是否为空
  34. let lat = "\(location.coordinate.latitude)"
  35. let long = "\(location.coordinate.longitude)"
  36. print("经纬度----\(lat),\(long)")
  37. callback!(lat,long)
  38. //停止定位
  39. locationManager.stopUpdatingLocation()
  40. }
  41. //出现错误
  42. func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
  43. print("error - \(error)")
  44. }
  45. func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
  46. locationManager.stopUpdatingLocation()
  47. }
  48. }