为什么我的 Collection View Cell 中显示为 nil?

Why do I get nil in my Collection View Cell?

我正在使用 Alamofire,但在那种情况下,当我调试时,Alamofire 代码不会执行,现在我尝试手动创建 url 并设置 headers,然后调用我的 API URL.

我的collection观点class如下

//
//  CategoryViewController.swift
//  iRate
//
//  Created by Ammar Khan on 16/08/2017.
//  Copyright © 2017 theistudio. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage

class CategoryViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate
{
    @IBOutlet var myCollectionView: UICollectionView!
    var catArr:[String] = []
    var catImage:[String] = []

    let categoriesUrl = "http://127.0.0.1:8000/api/places/categories"

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewDidAppear(_ animated: Bool) {

       loadCatList()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for:indexPath) as! CategoryCell
        print("Reached over here \(self.catArr.count)")
        cell.categoryName.text = self.catArr[indexPath.row]
        return cell
    }

    func loadCatList(){
        let networkSession = URLSession.shared

        var request = URLRequest(url: URL(string: self.categoriesUrl )!)

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let dataTask = networkSession.dataTask(with: request) { (data, response, error) in
            print("Data downloaded")

            let jsonReadable = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            print(jsonReadable!)
            do{

                let json = JSON(jsonReadable!)

                for (_,json):(String, JSON) in json {
                    let catName  = json["category_name"].stringValue
                    let catImage = json["image"].stringValue

                    self.catArr.append(catName)
                    self.catImage.append(catImage)
                }
            }
            catch{
                print("we have a JSON exception")
            }
        }
        //
        dataTask.resume()
        print("Downloading data")
    }

    func getCount(){
        print(self.catArr.count)
    }
}

我已经尝试了多种方法来将数据添加到我的词典中,但我失败了,结果是零。我不确定我在这里做错了什么。

PS:这不是我想要检索的内容,仅用于测试目的,因此只接收两个值并将它们添加到字典中。

最终结果:

因为下面建议的答案是问题之一,之后我接收数据并将它们附加到我的数组中的方式有​​些错误,所以在我的 do 语句中替换以下代码使其工作。

let json = JSON(data!)

print("The json data is \(json)")

for (_,json):(String, JSON) in json {

    let catName = json["category_name"].stringValue
    print("The catImage is \(catName)")
    let catImage = json["image"].stringValue
    self.catArr.append(catName)
    self.catImage.append(catImage)
}

DispatchQueue.main.async {
    self.myCollectionView.reloadData()
}

你接收到 nil 因为网络调用是异步的,所以当你的 table 显示时它是 nil ,当数据到来时你不会重新加载 collectionview,所以你需要添加以下内容在 JSON

的 for-in 循环之后
DispatchQueue.main.async {
  self.myCollectionView.reloadData()
}

更新:

您应该 return 项目数作为数据源中元素的数量,在本例中为 self.catArr,因此请按如下方式修改您的代码:

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