I'm coming from a javascript background and am finding it difficult to understand how to store the response from a simple GET request in SWIFT.
I have an empty array named plants
declared in my View Controller. The response from my GET request returns an array of plant names (strings). How can I assign the response array to the array plants
?
The setup of my code looks like this:
class MyPlantsViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addPlantTextField: UITextField!
var plants: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
getAllPlants()
}
func getAllPlants() {
// Create URL
let url = URL(string: ".....com/api/plants")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data {
<<..... I have tried lots of things here......>>
}
}
}
task.resume()
}
......