迅速。不在我的屏幕上显示数据。iOS 和 Firebase



我遇到了这样的问题。当我启动ios应用程序时,我会得到一个白色屏幕,并且我从Firebase获取的数据不会显示。我该如何解决这个问题?我将感谢你最喜欢的建议,以解决我的问题

这是我的ViewController

class ViewController: UIViewController {
    @IBOutlet weak var cv: UICollectionView!
    var channel = [Channel]()
    override func viewDidLoad() {
        
        super.viewDidLoad()
       
        self.cv.delegate = self
        self.cv.dataSource = self
        
        let db = Firestore.firestore()
        db.collection("content").getDocuments() {( quarySnapshot, err) in
            if let err = err {
                print("error")
            } else {
                for document in quarySnapshot!.documents {
                    if let name = document.data()["title"] as? Channel {
                        self.channel.append(name)
                    }
                    if let subtitle = document.data()["subtitle"] as? Channel {
                        self.channel.append(subtitle)
                    }
                    
        }
                self.cv.reloadData()
            }
}
    }
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return channel.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCell
        let channel = channel[indexPath.row]
        cell.setup(channel: channel)
        return cell
    }
    
    
}

这是我的型号

struct Content {
    let contents: [Channel]
}
struct Channel {
    let title: String
    let subtitle: String
}

这是我的手机

class ContentCell: UICollectionViewCell {
    
    @IBOutlet weak var channelText: UILabel!
    @IBOutlet weak var subtitle: UITextView!
    
    func setup(channel: Channel) {
        channelText.text = channel.title
        subtitle.text = channel.subtitle
    }
}

Firestore检索到的数据不能神奇地转换为您的自定义类型(Channel(;这是一本简单的字典。你需要使用Codable,或者像这样手动操作:

由于您没有在Firestore中共享数据的结构,我无法说出如何准确地转换它,但我认为这会起作用:

db.collection("content").getDocuments() { (snapshot, error) in
            if let error = error {
                print("error: (error.localizedDescription)")
            } else if let snapshot = snapshot {
                for document in snapshot.documents {
                    let data = document.data()
                    if let title = data["title"] as? String,
                       let subtitle = data["subtitle"] as? String {
                        
                        self.channel.append(Channel(title: title, subtitle: subtitle))
                    }
                }
            }
            
            self.cv.reloadData()
        }

最新更新