I'm working on a hobby project iOS app in Swift to learn using JSON with Moya. Here is how my VC code looks like:
import UIKit
import Moya
import Moya_ModelMapper
class SQSquirrelListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var squirrels: [Squirrel] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fetchData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func fetchData() {
let provider = MoyaProvider<SQService>()
provider.request(.squirrelsIndex(page: "1")) { result in
switch result {
case let .success(moyaResponse):
do {
let sq = try moyaResponse.mapObject() as Squirrels
self.squirrels = sq.items
} catch {
print(error.localizedDescription)
}
let statusCode = moyaResponse.statusCode
print("STATUS CODE: \(statusCode)")
case let .failure(error):
print(error.localizedDescription)
}
}
tableView.reloadData()
}
}
After launching the app the squirrels
array is empty. I'm not sure whether it's related to Moya or is it a flaw in the flow of my View Controller?
The line to reload the table view must be inside the completion handler.