View Controller

When the user has clicked on the “Find” button the following function is executed in the view controller:

@IBAction func didSubmit() {

if let text = self.textField?.text {

if text.count == 3 {

self.textField?.textColor = .black // status code is valid

self.textField?.text = nil



let newCat = CatStatus(value: text)

self.cats.append(newCat)



let indexPath = IndexPath(row: cats.count - 1, section: 0)

tableView?.insertRows(at: [indexPath], with: .automatic)



newCat.updated = { [unowned self] in

DispatchQueue.main.async {

self.tableView?.reloadRows(at: [indexPath], with: .automatic)

}

}

newCat.makeRequest()

} else {

self.textField?.textColor = .red // status code has more or less than 3 digits

}

if text.count == 0 {

self.textField?.textColor = .black // status code is empty

}

}

}

We first check whether the text is not nil and the text length is 3 — this means we might have a valid status code and should add a new row to the tableview . We create a new CatStatus instance and add it to our cats list. Then we tell the tableview that a new row should be inserted.

Now comes the interesting part: we want to tell the new CatStatus to make an API request. We first set the updated variable so that we are notified when imageData is updated. If imageData has been updated we want the tableview to reload the corresponding row.

We then start the request.