逃避完成处理程序永远不会发生(Google Places API)

时间:2016-10-29 01:37:39

标签: swift google-places-api google-places

我正在构建一个使用Google Places API的应用。我目前有一个按钮,当点击时,获取当前GPS位置的地址。代码在我的视图控制器中:

var placesClient: GMSPlacesClient?

@IBAction func buttonTapped(_ sender: AnyObject) {
    placesClient?.currentPlace(callback: { (placeLikelihoods, error) -> Void in
        guard error == nil else {
            print("Current Place error: \(error!.localizedDescription)")
            return
        }

        if let placeLikelihoods = placeLikelihoods {
            let place = placeLikelihoods.likelihoods.first?.place
            self.addressLabel.text = place?.formattedAddress!.components(separatedBy: ", ").joined(separator: "\n")
        }
    })
    print("Out of the brackets...")
}

完成此操作后,功能完成,并打印出“括号外...”。

但是,当我尝试将此代码移出视图控制器并进入自定义类并从视图控制器调用它时,如下所示,“placesClient?.currentPlace(回调”块中的所有内容都会运行(并检索正确的)地址),但“从括号中......”永远不会打印出来,它永远不会返回值:

class LocationAPIService {
var placesClient: GMSPlacesClient? = GMSPlacesClient.shared()

func getCurrentLocation() -> GMSPlace? {
    var thisPlace: GMSPlace?

    placesClient?.currentPlace(callback: { (placeLikelihoods, error) -> Void in
        guard error == nil else {
            print("Current Place error: \(error!.localizedDescription)")
            return
        }

        if let placeLikelihoods = placeLikelihoods {
            let place = placeLikelihoods.likelihoods.first?.place
            thisPlace = place
        }
    })
    print("Out of the brackets...")
    return thisPlace
}
}

有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

修正了它。这是我在LocationAPIService类中用于该方法的代码:

func setCurrentLocationPlace(completion: @escaping (_ result: Bool)->()) {
    var placeFindComplete: Bool = false

    placesClient?.currentPlace(callback: { (placeLikelihoods, error) -> Void in
        guard error == nil else {
            print("Current Place error: \(error!.localizedDescription)")
            completion(true)
            return
        }

        if let placeLikelihoods = placeLikelihoods {
            let place = placeLikelihoods.likelihoods.first?.place
            self.currentPlace = place
            placeFindComplete = true
            completion(true)
        }
    })
    if (placeFindComplete == false) {
        completion(false)
    }
}

以下是我从视图控制器调用它的方式:

locationAPIService?.setCurrentLocationPlace() { (locationFound) -> () in
        if (locationFound == true) {
//Run code here that triggers once setCurrentLocationPlace() complete.
}