Проблема извлечения пользовательских данных из firebase в VC1 и отправки их в TableView в VC2 для отображения - PullRequest
1 голос
/ 09 апреля 2019

У меня проблема с извлечением всех данных из Firebase Firestore (который отслеживает некоторую информацию о пользователе, например, title, description и imageURL), затем загрузкой изображения из firebaseStorage, созданием объекта с именем Cella (title: String, description: Строка, изображение: UIImage). Этот процесс должен происходить в цикле, который затем создает объект для каждого пользователя и возвращает массив объектов Cella для передачи другому ViewController и отображения в его tableView.

Я попытался исправить обработчики завершения, потому что я думал, что они были проблемой, а затем я добавил IBAction, который запускается при выполнении перехода.

ViewController, в котором я пытаюсь получить данные (обратите внимание, что они находятся внутри контроллера Navigation View, и segue является единственным, который запускается при нажатии этой кнопки).

class ViewController: UIViewController {

let firestoreUsersReference = Firestore.firestore().collection("users")
let storageReference = Storage.storage()

var cellaObjects : [Cella] = []


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    getDocumentsFromFirestore(firestoreReference: firestoreUsersReference) { (cellaArray) in
        self.cellaObjects = cellaArray
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

func getImagesDownloaded(reference: StorageReference, completion: @escaping (UIImage?,Error?)->()) {
    reference.getData(maxSize: 10*1024*1024) { (data, error) in
        guard error == nil, let data = data else {
            completion(nil,error)
            return
        }
        guard let image = UIImage(data: data) else {
            completion(nil, FirebaseErrors.expectedImage)
            return
        }
        completion(image,nil)
    }
}
enum FirebaseErrors: Error {
    case expectedImage
}


func getDocumentsFromFirestore (firestoreReference: CollectionReference, completion: @escaping ([Cella])->()) {


    var cellaArray : [Cella] = []

    firestoreUsersReference.getDocuments { (querySnapshot, err) in
        if err != nil {
            print("There has been an error \(String(describing: err?.localizedDescription))")
        }
        else {

            for documents in querySnapshot!.documents {
                print("\(documents.documentID) => \(documents.data())")
                let data = documents.data()
                let title = data["userTitle"] as! String
                let description = data["userDescription"] as! String
                let imageURL = data["userImageURL"] as! String
                print("Title: \(String(describing: title)), Description: \(String(describing: description)), imageURL: \(imageURL)")

                self.cellCreationProcess(title: title, description: description, imageURL: imageURL, completion: { (newCell) in
                    cellaArray.append(newCell)
                })


                }
            completion(cellaArray)
            }

        }
    }

func cellCreationProcess(title: String, description: String, imageURL: String, completion: @escaping (Cella) -> ()) {

    let storagePath = Storage.storage().reference(forURL: imageURL)

    self.getImagesDownloaded(reference: storagePath, completion: { (image, error) in
        guard let image = image, error == nil else {
            print(String(describing : error?.localizedDescription))
            return
        }
        print("TITLE: \(String(describing: title)), IMAGE: \(image)")
        let newCell = Cella(image: image, title: title, bodyMessage: description)
        completion(newCell)
    })

}

}

ViewController, где TableView:

class ViewControllerForTable: UIViewController, UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let currentCell = tableView.cellForRow(at: indexPath) as! TableViewCell

    let information = Information(title: currentCell.title.text!, description: currentCell.bodyText.text!, sellerImage: currentCell.CellImage.image!)

    let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerDisplay") as! ViewControllerDisplay

    destinationVC.dataPassed = information

    self.navigationController?.pushViewController(destinationVC, animated: true)
}


@IBOutlet weak var UITableView: UITableView!


let image : UIImage = UIImage(named: "image1")!

var cells : [Cella] = []

override func viewDidLoad() {
    super.viewDidLoad()

    //states that this class is the delegate of the data and the object tableView within this VC
    UITableView.delegate = self
    UITableView.dataSource = self

    //force sets each of the the tableView rows to have a height of 200
    UITableView.rowHeight = 200

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

//Function hardcoded that creates the 5 cells to test the app

//MARK - Table view settings

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //meaning my UITableView is going to have cells.count different rows
    return cells.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    //Gets each item singularly in order from the dictionary of cells
    let cellFormat = cells[indexPath.row]

    //You need to do this Nib thing because you created a xib file

    let nib = UINib(nibName: String(describing: TableViewCell.self), bundle: nil)

    tableView.register(nib, forCellReuseIdentifier: "customCell")

    // Says that it is going to create a reusable cell with the identifier from the XIB file and it is going to use the class TableViewCell to access its properties
    let cellObject = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TableViewCell

    //Creates and assigns the values from the item in the dictionary to the CellFormat for them to be displayed in the custom cell

    cellObject.setCell(cellFormatTaken: cellFormat)

    // returns the final Cell Item

    return cellObject

}

@IBAction func unwindToActivitieslList(sender: UIStoryboardSegue) {
    let sourceViewController = sender.source as? ViewController
    let activities = sourceViewController?.cellaObjects
    cells = activities!
    UITableView.reloadData()
}
}

------------------ ОБНОВЛЕНИЕ ------------------ Я удалил

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    getDocumentsFromFirestore(firestoreReference: firestoreUsersReference) { (cellaArray) in
        self.cellaObjects = cellaArray
    }

}

и добавил кнопку @IBAction func sardiniaNePressed (_ отправитель: UIButton) {

    getDocumentsFromFirestore(firestoreReference: firestoreUsersReference) { (cellaArray) in
        self.cellaObjects = cellaArray
        self.performSegue(withIdentifier:"sardiniaNe",sender:nil)
    }
}

Я также добавил отправку, как любезно предложено. Тем не менее, хотя я не могу получить данные для отображения. Еще одна проблема, с которой я сталкиваюсь, заключается в том, что всякий раз, когда я нажимаю на нее, поскольку виртуальные контроллеры встроены в контроллер навигации, они создают «дубликат» целевого ViewController, и он продолжает это делать в течение всего времени, пока приложение открыто, оставив меня с множеством дубликатов, с пустыми строками.

1 Ответ

0 голосов
/ 09 апреля 2019

Вам нужно вызвать это значение за пределами prepare(for segue: (непосредственно в действии кнопки) и в завершении выполнить переход

getDocumentsFromFirestore(firestoreReference: firestoreUsersReference) { (cellaArray) in
    self.cellaObjects = cellaArray
    self.performSegue(withIdentifier:"segue",sender:nil)
}

Также здесь вам нужно DispatchGroup() как получение изображения для каждогоэлемент асинхронный

func getDocumentsFromFirestore (firestoreReference: CollectionReference, completion: @escaping ([Cella])->()) {


    var cellaArray : [Cella] = []

    firestoreUsersReference.getDocuments { (querySnapshot, err) in
        if err != nil {
            print("There has been an error \(String(describing: err?.localizedDescription))")
        }
        else {

            let g = DispatchGroup()

            for documents in querySnapshot!.documents {

                g.enter()
                print("\(documents.documentID) => \(documents.data())")
                let data = documents.data()
                let title = data["userTitle"] as! String
                let description = data["userDescription"] as! String
                let imageURL = data["userImageURL"] as! String
                print("Title: \(String(describing: title)), Description: \(String(describing: description)), imageURL: \(imageURL)")

                self.cellCreationProcess(title: title, description: description, imageURL: imageURL, completion: { (newCell) in
                    cellaArray.append(newCell)
                    g.leave()
                })


            }

            g.notify(queue: .main, execute: {
                 completion(cellaArray)
            })

        }

    }
}
...