简体   繁体   中英

how to print track data (swift)

So I have the following code printing out the following

[DRN1.Data(track: DRN1.Trackinfo(title: "Charly\'s Ballad (Original Mix)", artist: "Castle Queenside", imageurl: "covers.drn1.com.au/az_B1017197_Disc 1 Traxsource Nu Disco & Indie Dance_Castle Queenside.jpg"))]

However when I go to write

print(nowplaying.data.track.title)

I get errors and it won't even attempt to load the swift app

struct Nowplayng: Decodable{
    let data: [Data]
}

struct Data: Decodable{
    let track: Trackinfo
}
struct Trackinfo: Decodable {
    let title: String
    let artist: String
    let imageurl: String
}

works

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let jsonURLString = "https://api.drn1.com.au/station/playing"
        guard let feedurl = URL(string: jsonURLString) else { return }

        URLSession.shared.dataTask(with: feedurl) { (data,response,err)
            in

            guard let data = data else { return }

            do{
                let nowplaying = try JSONDecoder().decode(Nowplayng.self, from: data)
                    print(nowplaying.data)


            }catch let jsonErr{
            print("error json ", jsonErr)
            }

//            let dataAsString = String(data:data, encoding: .utf8)
//            print(dataAsString)
        }.resume()



    }

does not work

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let jsonURLString = "https://api.drn1.com.au/station/playing"
        guard let feedurl = URL(string: jsonURLString) else { return }

        URLSession.shared.dataTask(with: feedurl) { (data,response,err)
            in

            guard let data = data else { return }

            do{
                let nowplaying = try JSONDecoder().decode(Nowplayng.self, from: data)
                    print(nowplaying.data.track.title)


            }catch let jsonErr{
            print("error json ", jsonErr)
            }

//            let dataAsString = String(data:data, encoding: .utf8)
//            print(dataAsString)
        }.resume()



    }

data is an array you need to loop over it

nowplaying.data.forEach {
   print($0.track.title)
} 

If you care about the first item do

if let item = nowplaying.data.first {
   print(item.track.title)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM