ios - iTunes API - JSON 数组错误 Swift4,要求。在 Collection View 中显示为数组

标签 ios json swift

我的 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/

相关文章:

ios - 我的 Highscore 数量一直在上下波动。 Swift SpriteKit

php - 做一个jQuery $.post() 到一个PHP Controller,然后在中间返回到View,然后使用$.get() 继续Controller

swift - 如何检测商店场景中的节点触摸并将该节点的值传递给 Sprite 套件中的 GameScene

ios - 对齐 UIView 和 CAShapeLayer 时遇到问题

xcode - 如何引用 NSIndexPath?

ios - ReactiveCocoa : View doesn't update when ViewModel property changes

ios - NSDate 在 iOS 8.4 和 9.3 版本的模拟器上崩溃少于 5s

ios - 从 Storyboard中的 UIViewController 加载 UIView 不起作用

javascript - 可以把scss改成json吗?

javascript - 使用客户端代码创建文本文件