首页 > 解决方案 > TableView 在使用两个嵌套的 alamofire 请求滚动之前不显示数据

问题描述

我有两个服务给我带来数据,第一个给我经度和纬度。我将它们发送到谷歌位置服务以获取“formatted_address”,然后将此格式化地址填充到 TableView

func getData(){
    locDataArray.removeAll()

     let url = "http://someurl/Report/v1/TripReport?UserID=101&Username=ewe2020&DeviceID=2647&FromDate=25/10/2018%2006:00%20AM&lang=ar&ToDate=25/10/2018%2009:00%20PM"

        // or if you need the string
        print(url)

        Alamofire.request(url).responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let swiftyJsonVar = JSON(responseData.result.value!)

                if let data = swiftyJsonVar.stringValue.data(using: .utf8) {
                    if let json = try? JSON(data: data) {
                        for item in json["data"].arrayValue {
                            self.locDataArray.append(LocData(fromJson: item))
                        }
                    }

                    DispatchQueue.main.async{
                        self.getAddress()
                        self.table.reloadData()
                    }
                }
            }
        }
}

获取位置的 long 和 lat 以及 google api :

for loc in self.locDataArray{

    let urlComponents = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+loc.fromLat!+","+loc.fromLong!+"&key=*************")!

    Alamofire.request(urlComponents).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)
            self.locNameFrom.append((swiftyJsonVar.dictionary!["results"]?[0]["formatted_address"].string)!)
        } else {
            print("empty")
        }
    }
}

最后,在 cellForRowAt

if locNameFrom.count > 0 {
    cell?.from.text = locNameFrom[indexPath.row]
}

数据仅在向上或向下滚动后显示。

标签: swiftuitableviewalamofireswifty-json

解决方案


if((responseData.result.value) != nil) {
                let swiftyJsonVar = JSON(responseData.result.value!)

                self.locNameFrom.append((swiftyJsonVar.dictionary!["results"]?[0]["formatted_address"].string)!)
                self.table.reloadData() // <-- here you should reloadData.
            }

推荐阅读