基于当前电台切换JSON链接加载TableView的实现问询
Hey there! Sounds like you're halfway there—great job getting the current station info passed to your JSONTableViewController already. Let's walk through how to tie that to loading the right JSON data for each station, step by step.
1. Create a Mapping Between Stations and Their JSON URLs
First, you need a clear way to link each radio station to its corresponding JSON endpoint. The safest approach here is to use an enum (if you have defined station types) or a dictionary (if you're using string identifiers for stations).
Option A: Use an Enum (Type-Safe)
If you haven't already, define an enum for your stations that includes the JSON URL as a computed property:
enum RadioStation { case indieFM case jazzBlues case classicRock case talkRadio // Replace with your actual station names var jsonEndpoint: String { switch self { case .indieFM: return "https://your-api-url.com/indie-fm-data.json" case .jazzBlues: return "https://your-api-url.com/jazz-blues-data.json" case .classicRock: return "https://your-api-url.com/classic-rock-data.json" case .talkRadio: return "https://your-api-url.com/talk-radio-data.json" } } }
Option B: Use a Dictionary (For String Identifiers)
If you're passing station names as strings, a dictionary will work just fine:
let stationURLMap: [String: String] = [ "Indie FM": "https://your-api-url.com/indie-fm-data.json", "Jazz & Blues": "https://your-api-url.com/jazz-blues-data.json", "Classic Rock": "https://your-api-url.com/classic-rock-data.json", "Talk Radio": "https://your-api-url.com/talk-radio-data.json" ]
2. Add Logic to Load Data Based on the Current Station
In your JSONTableViewController, add a property to hold the current station, then use a method to fetch the corresponding JSON data.
Example Implementation
class JSONTableViewController: UITableViewController { // Replace with your station type (RadioStation enum or String) var currentStation: RadioStation? { didSet { // Automatically reload data when the station changes loadStationData() } } // Your data source for the table view private var stationData: [YourDataModel] = [] // Replace with your actual model type override func viewDidLoad() { super.viewDidLoad() // Load data when the view first appears loadStationData() } private func loadStationData() { guard let station = currentStation else { // Handle the case where no station was passed (e.g., show an empty state) print("No current station provided") stationData = [] tableView.reloadData() return } // Get the correct URL based on the station let targetURL = station.jsonEndpoint // Use stationURLMap[station] if using strings // Fetch and parse the JSON fetchJSON(from: targetURL) } private func fetchJSON(from urlString: String) { guard let url = URL(string: urlString) else { print("Invalid URL for station data") return } URLSession.shared.dataTask(with: url) { [weak self] data, response, error in guard let self = self else { return } // Handle network errors if let error = error { print("Failed to fetch data: \(error.localizedDescription)") DispatchQueue.main.async { // Update UI to show error (e.g., alert or empty state) self.stationData = [] self.tableView.reloadData() } return } // Parse the JSON data guard let data = data else { print("No data received from the endpoint") DispatchQueue.main.async { self.stationData = [] self.tableView.reloadData() } return } do { // Replace [YourDataModel].self with your actual model type let parsedData = try JSONDecoder().decode([YourDataModel].self, from: data) DispatchQueue.main.async { // Update the table view with the new data self.stationData = parsedData self.tableView.reloadData() } } catch { print("Failed to parse JSON: \(error.localizedDescription)") DispatchQueue.main.async { self.stationData = [] self.tableView.reloadData() } } }.resume() } // MARK: - Table View Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return stationData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) let item = stationData[indexPath.row] // Configure your cell with the data cell.textLabel?.text = item.title // Replace with your model's properties return cell } }
3. Key Notes to Remember
- Thread Safety: Always update your table view on the main thread (we use
DispatchQueue.main.asyncfor this in the network callback). - Error Handling: Don't forget to handle cases like invalid URLs, network failures, and JSON parsing errors—your users will appreciate clear feedback if something goes wrong.
- Automatic Updates: The
didSetproperty observer oncurrentStationensures that if the user switches stations while the table view is visible, the data will reload automatically.
That's it! This setup will make sure your JSONTableViewController always loads the correct data based on the currently playing radio station.
内容的提问来源于stack exchange,提问作者Manuel Duarte

