Swift:使用字典将Alamofire中的JSON数据解析为数组时出错

时间:2018-11-06 13:42:42

标签: ios json swift sdwebimage

我收到以下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)")
            }
        }

    }
}

运行时它显示黑屏

2 个答案:

答案 0 :(得分:0)

实际上,就像Scrpitable所说的那样,黑屏代码可能与您无关。例如,每当我出现黑屏时,我首先要检查的是对其中一个视图的“ Is Initial View Controller”进行了检查。有时,如果我忘记设置初始视图,它只会显示黑屏。我将在屏幕快照中添加我的意思。enter image description here

答案 1 :(得分:0)

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

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

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