Прежде всего объявляйте переменные в вашем контроллере представления или в другом месте.
var mArray:[Music] = []
Попробуйте использовать Codable / Decodable Json parse для получения ApiResults,
struct ApiResults:Decodable {
let resultCount: Int
let results: [Music]
}
struct Music:Decodable {
let artistId: Int?
let artistName: String?
let country: String?
let currency: String?
let kind: String?
}
Теперь попробуйте вваш viewdidload или вызовите его как функцию, где бы вы ни хотели ...
func callAPI() {
guard let url = URL(string: "https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo") else {return}
URLSession.shared.dataTask(with: url){(data, response, error) in
guard let data = data else {return}
do
{
let apiressults = try JSONDecoder().decode(ApiResults.self, from: data)
for item in apiressults.results
{if let track_Name = item.trackName, let artist_Name = item.artistName, let country = item.country, let currency = item.currency, let kind = item.kind
{let musics = Music(artistId: artist_Id, artistName: artist_Name, country: country, currency: currency, kind: kind)
self.mArray = apiressults.results
}
}
DispatchQueue.main.async
{
self.collectionView.reloadData()
} }
catch let jsonError
{
print("Error:", jsonError)
}
}.resume()
}
Теперь, наконец, как вы упомянули, чтобы показать его в виде коллекции как массив / список.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell // your cell identifier..
cell.label1.text = mArray[indexPath.row].trackName
cell.label2.text = mArray[indexPath.row].trackId
cell.label3.text = mArray[indexPath.row].currency.
///////like so for other stuffs which u need to show in collection view.
}
return cell
}