异步功能输出不起作用

时间:2018-08-15 04:35:30

标签: ios asynchronous swift4 google-distancematrix-api

我正在使用Google Maps距离矩阵api编写程序,目前这是我的代码:

func loopFinalRoutes(){
    self.indexEachArray = 0
    let eachArray = finalRoutes[indexFinalRoutes]
    loopEachArray(eachArray: eachArray) { (success) in
        self.indexFinalRoutes = self.indexFinalRoutes + 1
        if self.indexFinalRoutes < self.finalRoutes.count - 1{
            self.loopFinalRoutes()
        }else{
            self.indexFinalRoutes = 0
            print("hello")
            print(self.groupedDurations)
        }
    }
}

func loopEachArray(eachArray : [String] ,
                   completion: @escaping (_ success:Bool) -> Void){
    if indexEachArray + 1 < eachArray.count - 1 {
        configureRoute(origin: eachArray[indexEachArray], destination: eachArray[indexEachArray+1]){
            duration in
            self.durations.append(duration)
            self.indexEachArray = self.indexEachArray + 1
            let nextEachArray = self.finalRoutes[self.indexFinalRoutes]
            self.loopEachArray(eachArray: nextEachArray, completion: completion)
        }
    }else{
        groupedDurations.append(durations)
        durations.removeAll()
        completion(true)
    }

}

func configureRoute(origin:String,destination:String, completionHandler: @escaping (_ duration:Int) -> ()){
    let jsonURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=place_id:\(origin)&destinations=place_id:\(destination)&key=AIzaSyAmx6h2aX9Jqfo4BrZ-ZjB-SbQ8phau-EE"
    guard let url = URL(string: jsonURL ) else {return}
    print(jsonURL)
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else {
            return
        }
        do{
            let route = try JSONDecoder().decode(Welcome.self, from: data)
            print(self.durations)
            print(self.groupedDurations)

            completionHandler(route.rows[0].elements[0].duration.value)
        }
        catch let jsonErr{
        }
        let dataAsString = String(data: data, encoding: .utf8)
        }.resume()
}

因此,理想情况下,当我以4个目标(包括开始和结束目标)运行此程序时。它应该将中间的2个目标(可以成功运行)随机播放,然后应该计算它们之间的距离并将它们附加到数组中。因此,如果我有4个目标,它们看起来应该像一个数组,其中有2个数组,并且每个数组中有3个元素。

但这就是现在的输出:[[25,1041]]

0 个答案:

没有答案