Search code examples
iosswifttableviewalamofire

cellForRowAtIndexPath not called when using with Alamofire


I made a function that calls list of user api and I put it in viewDidLoad so that I can get the list in TableViewCell as soon as screen get loaded.

But the problem is after calling of numberOfRowsInSection, Alalmofire.rquest gets called automatically and cellForRowAtIndexPath not getting called hence TableView is empty.

 func userList(){

    let header = [

         "some header":"SomeHeaderValue"
    ]

    var request = BaseUrl + "userList"

    let parameters = ["":""]

    var encodingFormat: ParameterEncoding = URLEncoding()
    if request == "" {
        encodingFormat = JSONEncoding()
    }

    Alamofire.request(request, method: .get, parameters: parameters, encoding: encodingFormat, headers: header).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            if let data = response.result.value{
                print(response.result.value)

                self.userArray = data as! [AnyHashable]

            }
            break

        case .failure(_):
            print(response.result.error)
            break
        }
   }
}

Solution

  • Network calls are asynchronous and take time. You need to reload the tableView after receiving the data.

     Alamofire.request(request, method: .get, parameters: parameters, encoding: encodingFormat, headers: header).responseJSON { (response:DataResponse<Any>) in
    
            switch(response.result) {
            case .success(_):
                if let data = response.result.value{
                    print(response.result.value)
    
                    self.userArray = data as! [AnyHashable]
                    print(self.groupArray)
                    print(self.groupArray.count)
                    DispatchQueue.main.async {
                        tableView.reloadData()
                    }
                }
    
                break
    
            case .failure(_):
                print(response.result.error)
                break
            }
       }