【问题标题】:Getting collection and saving it into array object in firestore swift获取集合并将其保存到firestore swift中的数组对象中
【发布时间】:2022-01-22 10:11:09
【问题描述】:

我正在尝试将集合保存到一个名为 List 的对象数组中,并且该检索是由函数 loadfirebase 在 vi​​ewdidload 中调用的。所以它实际上从 firebase 检索数据并打印它,但它不会将它保存在数组中。我认为这是处理关闭但不知道如何解决它的问题。

//
//  ContactList.swift
//  Socket
//
//  Created by dalal aljassem on 12/16/21.
//

import UIKit
import FirebaseFirestore
import FirebaseStorage

class ContactList: UIViewController, UITableViewDelegate, UITableViewDataSource {
    private  let storage  = Storage.storage().reference()
   
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return List.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell" , for:indexPath)
        var currentname = List[indexPath.row]
        cell.textLabel?.text = currentname.name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        print("some action will happen when i tap here")
    }
    

    @IBOutlet var tableView: UITableView!
     
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
       
        loadfirebase()
        print("**************",List)
    }
   
}
let database = Firestore.firestore()
func loadfirebase()
{
    let contactdataRef = database.collection("ContactData")
   contactdataRef.getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
             //   var currentDoc = document.data()
                
                print("///////////////")
                // print("current doc = " , currentDoc)
                print("current name = " , document.get("name")!)
                print("current image = " , document.get("image")!)
            List.append(Contact(name: document.get("name") as! String, image: document.get("image") as! String, number: ""))
               
                print("\(document.documentID) => \(document.data())")
            }
        }

   }}
    
}

【问题讨论】:

    标签: ios swift firebase uikit


    【解决方案1】:

    您的 List 数组从未初始化。 您可以使用以下代码实现此目的:

    var List: [Contact] = []
    

    我会把它放在 tableView 函数的声明之前。

    【讨论】:

    • 当我打印数组时它仍然是空的?你知道该怎么做吗?
    • 如果您指的是这段代码:print("**************",List),那么请注意它可能会在 loadfirebase() 之前执行,因为您在 loadfirebase 中有一个异步调用,它将在 print 语句之后完成.尝试在 getDocuments 回调中打印列表,它应该可以工作
    • 问题是它没有保存到数组中
    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2021-05-01
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多