1

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()
    }
......

1 Answers1

2

You can use JSONDecoder to decode list of string as below,

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error {
        print("error: \(error)")
    } else {
       do {
           self.plants = try JSONDecoder().decode([String].self, from: data!)
       } catch {
           print(error)
       }
    }
}
Kamran
  • 13,636
  • 3
  • 26
  • 42
  • 1
    Thank you so much! That worked. Side Note: was having trouble since it didnt load to my table after the get request completed. I added `DispatchQueue.main.async{ self.tableView.reloadData() }` and it populated my table. – bradleyZazz Apr 20 '20 at 23:02
  • As a follow up @Kamran, if I wanted to include a parameter in my GET request, for example a plant name to get the information about a specific plant, how would I go about doing that? – bradleyZazz Apr 21 '20 at 17:47
  • @bradleyZazz To send parameters, it should be a post request. But for a get request if necessary you can make parameters as part of the urlString. You can check this [answer](https://stackoverflow.com/a/27724627/2395636) to send parameters with get request. – Kamran Apr 21 '20 at 18:14