display a list of tour items retrieved from a url in swift

You can retrieve a list of tour items from a URL in Swift by making an HTTP request to the server using URLRequest and URLSession. The data retrieved from the URL can be in JSON format, which can be parsed using Apple’s JSONSerialization API. Once the data has been parsed, you can display it in a UITableView with custom UITableViewCell.

Here's an example code snippet to get started:

main.swift
import UIKit

struct Tour: Codable {
    let title: String
    let description: String
}

class ViewController: UIViewController, UITableViewDataSource {

    var tours: [Tour] = []

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set the tableview datasource
        tableView.dataSource = self

        // Retrieve tours from API
        let url = URL(string: "https://example.com/api/tours")!
        var request = URLRequest(url: url)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: { data, response, error in
            guard let data = data else {
                print("Error retrieving data")
                return
            }

            if let tours = try? JSONDecoder().decode([Tour].self, from: data) {
                DispatchQueue.main.async {
                    self.tours = tours
                    self.tableView.reloadData()
                }
            }
        })

        task.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tours.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TourCell", for: indexPath) as! TourCell

        // Configure the cell with tour data
        let tour = tours[indexPath.row]
        cell.titleLabel.text = tour.title
        cell.descriptionLabel.text = tour.description

        return cell
    }
}

class TourCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
}
1814 chars
63 lines

In the above example, we defined a Tour struct with the title and description properties. We then created a UITableView with custom TourCell that displays the title and description of each tour item. The viewDidLoad function sends a request to the server and upon receiving the response, it parses the JSON data into an array of Tour objects. Finally, the table view is reloaded with the retrieved tours array.

gistlibby LogSnag