【问题标题】:Why do I get nil in my Collection View Cell?为什么我的 Collection View 单元格中得到 nil?
【发布时间】:2018-01-28 10:49:28
【问题描述】:

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

我的收藏视图类如下。

//
//  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:这不是我想要检索的,只是为了测试目的,因此只接收两个值并将它们添加到 dict。

最终结果:

正如下面建议的答案是问题之一,之后我接收数据并将它们附加到我的数组中的方式有​​些错误,因此在我的 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()
}

【问题讨论】:

    标签: ios api swift3 uicollectionviewcell


    【解决方案1】:

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

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

    更新:

    您应该将项目数作为数据源中的元素数返回,在本例中为 self.catArr,因此修改您的代码如下:

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

    【讨论】:

    • 我已将其粘贴到我的 do 语句中,就在 for 循环之后。问题仍然没有解决。应用程序一启动它就会崩溃并给我一个超出范围的索引。它首先加载 cellForItemAt 函数,然后由于数据尚未加载而中断
    • @indexOutOfBounds 请检查我的更新答案,并提供您的反馈
    • 出于测试目的,我将部分返回 2 但它解决了错误。谢谢你,但问题仍然存在。 cellforItemAt 函数不会执行,因此当应用程序启动时不会显示任何内容。计数仍为 0。
    • @indexOutOfBounds 它没有显示数据,因为在应用程序开始时您在 arr 中没有元素,您需要在开始时填充数组,因为您的 loadCatList 方法是异步网络调用,所以加载数据需要一些时间,希望对您有所帮助
    • 我在加载我的 loadCatList() 函数中的数据时填充数组?我应该在 viewDidLoad() 中调用该函数吗?下载数据后,我必须填充它们,这就是我正在做的事情。我已经对其进行了调试,即使在调用了下载的数据之后,它也会返回计数为 0。您会在控制台中看到打印的数据,然后计为 0
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多