Как получить элемент из документа в хранилище Firebase и добавить его в представление с помощью SWIFT - PullRequest
0 голосов
/ 18 июня 2020

Я пытаюсь получить переменную "name" из документа Firestore (UserProfileV C) и добавить ее в заголовок (UserProfileHeader), но у меня возникают проблемы с получением данных в нужном мне формате. В настоящее время я получаю следующее сообщение об ошибке для строки «userReference.getDocument {(снимок) в» в UserProfileV C. Я пробовал несколько разных способов, но ничего из того, что я пробовал, не помогло. Что я делаю не так или есть лучший способ организовать данные? Я новичок в SWIFT, поэтому мое решение может быть неуместным!

Сообщение об ошибке:

Тип контекстного закрытия '(DocumentSnapshot ?, Ошибка?) -> Void 'ожидает 2 аргумента, но 1 был использован в теле закрытия

Модель - Класс пользователя:

class User{

    var username: String!
    var name: String!
    var uid: String!

    init(uid: String, dictionary: Dictionary<String, AnyObject>) {
        self.uid = uid
        if let username = dictionary["username"] as? String {
            self.username = username
        }
        if let name = dictionary["name"] as? String {
            self.name = name
        }
    }

Просмотр - UserProfileHeader:

var user: User? {
        didSet {
            let fullName = user?.name
            nameLabel.text = fullName

            guard let profileImageUrl = user?.profileImageUrl else { return }
            profileImageView.loadImage(with: profileImageUrl)
        }
    }

Контроллер - UserProfileV C:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! UserProfileHeader

        header.delegate = self

        header.user = self.user
        navigationItem.title = user?.username

        return header
    }

func fetchCurrentUserData() {

    guard let currentUid = Auth.auth().currentUser?.uid else { return }
    let db = Firestore.firestore()
    let userReference = db.collection("profile_data").document(currentUid)

    userReference.getDocument { (snapshot) in
        guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return }
        let uid = snapshot.key
        let user = User(uid: uid, dictionary: dictionary)
        self.user = user
        self.navigationItem.title = user.username
        self.collectionView?.reloadData()
    }
}  

1 Ответ

1 голос
/ 18 июня 2020

Обновление: измените весь свой код внутри fetchCurrentUserData, чтобы он соответствовал новой документации Firbase .

Внутри метода fetchCurrentUserData закрытие userReference.getDocument имеет два параметра вместо просто измените это, и все будет хорошо, вот как:

func fetchCurrentUserData() {
    guard let currentUid = Auth.auth().currentUser?.uid else { return }
    let db = Firestore.firestore()
    let userReference = db.collection("profile_data").document(currentUid)

    userReference.getDocument { (document, error) in
        if let document = document, document.exists {
            let dictionary = document.data()
            let uid = snapshot.key
            let user = User(uid: uid, dictionary: dictionary)
            self.user = user
            self.navigationItem.title = user.username
            self.collectionView?.reloadData()
        }
    }
}
...