Home > Back-end >  Getting API Result with closure and passing it into an other ViewController
Getting API Result with closure and passing it into an other ViewController

Time:12-11

I'm getting an API Result in my viewModel as below:

class HomePageViewModel {

var apiResult: CountryDataFromAPI?

//Getting API result via viewModel

public func getAPIResult(withOffset: Int, completion: @escaping () -> Void) {
    APIHandler.urlRequest(with: withOffset) { result in
        self.apiResult?.data.append(contentsOf: result.data)
        print("api resultdata in viewmodel is \(result.data)")
        completion()
    }
 }
}

Getting the api works fine. In the code above, I can print the statement as print("api resultdata in viewmodel is (result.data)") and see the expected api result.

When I get the data inside my viewModel as above, I use it in my mainViewController.

My mainViewController is initialized with the ViewModel

class HomePageViewController: UIViewController {

private var viewModel : HomePageViewModel
private var countryDataArray: [CountryData]?

init(with viewModel: HomePageViewModel) {
    self.viewModel = viewModel
    super.init(nibName: nil, bundle: nil)
 }
}

Everything works fine until I try to get the data from viewModel as below. I'm trying to set the data in ViewModel to a parameter called countryDataArray. But while doing that inside the closure, my print statement "print("data in vc is (self?.viewModel.apiResult?.data)")" prints out nil even though it gets the data in viewModel.

override func viewDidLoad() {
    super.viewDidLoad()
    //Getting API Result in viewDidLoad. And after getting the result, reloading the tableView.
    self.viewModel.getAPIResult(withOffset: 11) { [weak self] in
        DispatchQueue.main.asyncAfter(deadline: .now()   2, execute: {
            self?.countryDataArray = self?.viewModel.apiResult?.data
            print("data in vc is \(self?.viewModel.apiResult?.data)")
            self?.countriesListTableView.reloadData()
        })
    }
}

Why this might be happening?

PS: My api models are as below:

struct CountryDataFromAPI: Codable {
var data: [CountryData]
}

struct CountryData: Codable,Equatable {
let name : String
let code: String
let wikiDataId: String    
}

CodePudding user response:

In my opinion, the problem is the self.apiResult?.data.append(contentsOf: result.data)

You didn't assign any value for the apiResult.data. Because apiResult is nil.

You have to initialize the apiResult after you get data back from API.

  • Related