如何在多个ViewController中使用locationManager()

fs_tigre

我需要在多个viewControllers中获取zipCodecity

这是我目前正在做的事情...

import CoreLocation
let locationManager = CLLocationManager()

class MyViewController: UIViewController, CLLocationManagerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
            if error != nil {
                //AlertView to show the ERROR message
            }

            if placemarks!.count > 0 {
                let placemark = placemarks![0]
                self.locationManager.stopUpdatingLocation()
                let zipCode = placemark.postalCode ?? ""
                let city:String = placemark.locality ?? ""

                // Do something with zipCode
                // Do something with city
            }else{
                print("No placemarks found.")
            }
        })
    }

 func someFunction() {
    locationManager.startUpdatingLocation()
 }

一切正常,但正如您所看到的,在多个viewController中这样做会导致很多代码重复(当然,我没有显示整个代码)。

什么是检索最常用的方法zipCode,并cityCLLocationManager()从多个viewControllers一个更实际的方法是什么?

我在想的是...

 MyLocationManager.zipCode() // returns zipCode as a string 
 MyLocationManager.city() // returns city as a string 
谦虚

我尝试实现单例CLLocationManager类,我认为您可以修改以下类以实现一些其他方法。

import Foundation

class LocationSingleton: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var latitude = 0.0
private var longitude = 0.0

static let shared = LocationSingleton()

private override init() {
    super.init()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
    locationManager.requestAlwaysAuthorization() // you might replace this with whenInuse
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        latitude = location.coordinate.latitude
        longitude = location.coordinate.longitude
    }
}

private func getLatitude() -> CLLocationDegrees {
    return latitude
}

private func getLongitude() -> CLLocationDegrees {
    return longitude
}

private func zipCode() {
    // I think you can figure way out to implemet this method
}

private func city() {
    // I think you can figure way out to implemet this method
}
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章