Skip to content

Using External JSON #1

@redimongo

Description

@redimongo

I am having issues implementing your code on the following - We use JSON from a server

import SwiftUI
//import Combine
// Add this top level struct to
// decode properly

// PODCASTS
struct Post: Codable {
    var programs: [Program]
}

struct Program: Codable , Identifiable  {
  var id,title,url,icon,banner:String

  private enum CodingKeys : String, CodingKey {
    case id = "_id", title , url , icon , banner
  }
}

// STATION
struct Sdata: Codable {
    var data: [Station]
}

struct Station: Codable , Identifiable  {
  var id,name,imageurl,listenlive:String

  private enum CodingKeys : String, CodingKey {
    case id = "_id", name , imageurl , listenlive
  }
}




class Api {
   
    
    func getStations(completion: @escaping ([Station]) -> ()) {
        guard let url = URL(string: "https://api.EXAMPLE.com.au/station/allstations") else { return }
       
        
        URLSession.shared.dataTask(with: url) { (data, _, error) in
            
            if error != nil{
            //    getShows(station:\(station), completion: ([Program]) -> ())
            
                DispatchQueue.main.async{
                    // The array is stored under programs now
                  
                    completion([DRN1.Station(id: "0", name: "ERROR", imageurl: "https://storage.googleapis.com/radiomediapodcast/PopYourCherri/PopYourCherriLogo.png",listenlive: "ERROR")])
                }
                return
            }
            // Based on the updated structs, you would no
            // longer be decoding an array
            let station = try! JSONDecoder().decode(Sdata.self, from: data!)
            DispatchQueue.main.async{
                // The array is stored under station now
                completion(station.data)
            }
            
        }
    .resume()
    }
    
    
 
}

which in SwiftUI all I have to do is

Api().getStations { (stations) in
                       self.stations = stations
        }

How do I implement this into your code please.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions