繁体   English   中英

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)
            }
        }
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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