尝试使用尚未从自身检索到的数据后,将调用委托方法didUpdateLocations-Xcode Swift

时间:2019-03-02 06:17:07

标签: ios swift core-location cllocationmanager

我有一个NS对象(称为GoogleSearch),用于获取用户的位置数据。这些是创建的一些全局变量和init函数:

let locationManager = CLLocationManager()
var coordinates: CLLocationCoordinate2D?

override init() {
    super.init()
    print("1")
    DispatchQueue.main.async {
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        if CLLocationManager.locationServicesEnabled() {
            self.locationManager.startUpdatingLocation()
        }
    }

}

接下来,这是我的委托方法:

extension GoogleSearch: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("2")
    let userLocation: CLLocation = locations[0] as CLLocation
    self.coordinates = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
}
}

接下来,我尝试在以后的函数中访问坐标(在委托方法中设置):

func searchForPlaces(completion: @escaping ([place])->()) {
    print(coordinates)
}

最后,在实现此 NSobject ViewController 中,viewDidLoad中包含以下代码:

self.googleSearch = GoogleSearch()
    DispatchQueue.main.async {
        self.googleSearch.searchForPlaces(completion: { (places) in
            DispatchQueue.main.async {
                self.places = places
                self.placesCollectionView.reloadData()
            }
        })
    }

问题是在searchForPlaces函数中打印坐标会打印nil,因为它是在调用委托方法之前运行的。我应该在NSObject或ViewController中进行任何更改,以确保可以从searchForPlaces()访问坐标吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式实现:

class GoogleSearch:NSObject {

  let locationManager = CLLocationManager()
  var coordinates: CLLocationCoordinate2D?
  var completionHandler: ((CLLocationCoordinate2D) -> Void)?

  override init() {
      super.init()
      print("1")

    }

   func searchForPlaces(completion: @escaping (CLLocationCoordinate2D) -> Void) {
     self.completionHandler = completion
     self.locationManager.delegate = self
     self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
     if CLLocationManager.locationServicesEnabled() {
        self.locationManager.stopUpdatingLocation()
        self.locationManager.startUpdatingLocation()
     }
   }
}


extension GoogleSearch: CLLocationManagerDelegate {
   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
     print("2")
     let userLocation: CLLocation = locations[0] as CLLocation
     self.coordinates = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
     self.completionHandler?(self.coordinates!)
    }
}