Swift:使用字典将来自 alamofire 的 JSON 数据解析为数组时出错

Swift: Error while Parsing JSON data from alamofire into array with Dictionary

我有以下 JSON 响应,我想获得 idurl

[
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
    "thumbnailUrl": "https://via.placeholder.com/150/92c952"
  }]

在视图控制器中,我的编码如下。

import UIKit
import Alamofire
import SDWebImage


class AlbumResponse: Codable {
    var list: Int
    var hits: [Album]
}


class Album: Codable {
    var id: Int
    var title : String
    var url: String
    var thumbnailUrl : String
}



class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    let url1 = ["JSON URL"]
    @IBOutlet weak var collection: UICollectionView!
    var arrList = [Album]()


    override func viewDidLoad() {
        super.viewDidLoad()
        reequest()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.collection.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrList.count

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
        let objct = arrList[indexPath.row]
        cell.label.text =  String(objct.id)
        cell.img!.sd_setImage(with: URL(string: objct.url), placeholderImage: #imageLiteral(resourceName: "download"), options: .retryFailed, completed: nil)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = (self.view.frame.size.width - 5 * 2 ) / 2 //some width
        let height = width * 1.45 //ratio
        return CGSize(width: width, height: height)
    }


    func reequest() {

        let url = URL(string: "JSON URL")
        Alamofire.request(url!).responseJSON {(response) in

            switch (response.result){
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode(AlbumResponse.self, from: data)
                        self.arrList = response.hits
                        DispatchQueue.main.async {
                        self.collection.reloadData()
                        }
                    } catch {
                        print(error.localizedDescription)
                    }
                }

            case .failure(let error):
                print("error to print the data \(error)")
            }
        }

    }
}

当我运行它显​​示黑屏

其实像Scrpitable说的黑屏可能跟你的代码没有关系。例如,每当我遇到黑屏时,我首先要检查的是 "Is Initial View Controller" 是否针对我的一个视图进行了检查。有时,如果我忘记设置初始视图,它只会显示黑屏。我会添加屏幕截图来说明我的意思。

我试过了,我找到了正确的方法。这是正确的代码。

import UIKit
import Alamofire
import SDWebImage


class Album: Codable {
    var url : String
    var id : Int
}


class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var collection: UICollectionView!
    var urls = URL(string: "my Url")

    var arrList = [Album]()

    override func viewDidLoad() {
        super.viewDidLoad()
        request()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

            let obj = arrList[indexPath.row]
        cell.label.text = String(obj.id)
        cell.imageview!.sd_setImage(with: URL(string: obj.url), placeholderImage: #imageLiteral(resourceName: "6-things-main"), options: .cacheMemoryOnly, completed: nil)
        return cell
    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = (self.view.frame.size.width - 1 * 2 ) / 2
    let height = width * 1.45
        return CGSize(width: width, height: height)
    }

    func request() {

        let url = URL(string: "my url")
        Alamofire.request(url!).responseJSON {(response) in

            switch (response.result) {
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode([Album].self, from: data)
                        self.arrList = response
                        DispatchQueue.main.async {
                            self.collection.reloadData()
                        }
                    } catch {
                        print(error.localizedDescription)
                    }
                }
            case .failure( let error):
                print(error)
            }
        }
    }
}

如果您仍然遇到任何问题,请发表评论。