我的 json 响应是,
{ resultCount = 32;
results = (
{
artistId = 909253;
artistName = "Jack Johnson";
country = USA;
currency = USD;
kind = "music-video";
},
{
artistId = 909253;
artistName = "Jack Johnson";
country = UK;
currency = USD;
kind = "music-video";
}
我已经编写了 View 加载的代码来调用get方法,
Alamofire.request("https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo").responseJSON { response in
debugPrint(response)
if let json = response.result.value //getting json
{
print(json)
let jobsArray : NSArray = json as! AnyHashable as! NSArray //converting json to NSArray
if jobsArray.count > 0
{
for object in jobsArray
{
if let singleDict = object as? NSDictionary
{
self.arrFavAdsList.add(singleDict)
print(self.arrFavAdsList)
}
}
DispatchQueue.main.async() {
self.collectionView.reloadData()
}
//displaying data in tableview
}
}
}
但它显示 json 数组错误..我需要将数组响应作为字典获取并将其显示在我的 Collection View 中
最佳答案
首先在你的 View Controller 或其他地方声明变量
var mArray:[Music] = []
尝试使用 Codable/Decodable Json 解析来获取 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()
}
现在终于,正如您提到的,为了在 Collection View 中将其显示为数组/列表。
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
}
关于ios - iTunes API - JSON 数组错误 Swift4,要求。在 Collection View 中显示为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54708620/