Search code examples
swiftuitableviewalamofireswifty-json

TableView not showing data until scrolling with two nested alamofire request


I have two services that bring me data, the first one gets me longitude and latitude. I send them to google location services to get me a "formatted_address", then fill this formatted address into a 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()
                    }
                }
            }
        }
}

for getting the location's long and lat and this for 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")
        }
    }
}

finally, in the cellForRowAt

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

the data is only shown after scrolling up or down.


Solution

  • 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.
                }