正确分配取决于闭包结果的变量值

时间:2019-05-17 18:18:58

标签: ios swift asynchronous closures

我的目标是检查我的用户当前是否位于两个目标国家之一。如果用户在以下国家之一中,则该应用会打印true,否则打印false

我已经成功地通过反向地理编码成功检索了用户的位置,因此下一步就是对照我的goalCountries数组检查该值。但是,我在关闭时遇到了问题:isUserInGoalCountry()内部执行关闭时,我的应用已经执行了检查并打印了false

class ViewController: UIViewController {

   let goalCountries = ["United States", "United Kingdom"]


    override func viewDidLoad() {
        super.viewDidLoad()

        if isUserInGoalCountry() {
            print(true) //never called because if stmt always executes before closure
        } else {
            print(false)
        }
    }




    func isUserInGoalCountry() -> Bool {

        var isUserInGoalCountry = false

        let locationManager = CLLocationManager()
        locationManager.delegate = self

        let latitude = locationManager.location?.coordinate.latitude ?? 0.0
        let longitude = locationManager.location?.coordinate.longitude ?? 0.0
        let coordinates = CLLocation(latitude: latitude, longitude: longitude)

        fetchCountry(from: coordinates) { (country, error) in
                if let error = error {
                    print("Could not retrieve user's current country: \(error.localizedDescription)")
                    return
                }
                if let country = country {
                    isUserInGoalCountry = true
                }
         }
    }


    // Helper function for isUserInGoalCountry()

    private func fetchCountry(from location: CLLocation, completion: @escaping (_ country:  String?, _ error: Error?) -> ()) {
        CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
            completion(placemarks?.first?.country, error)
    }
}

我了解此错误的根源:闭包是异步执行的。我该如何工作?

0 个答案:

没有答案