Почему моя модель не показывает свой элемент в контроллере представления? - PullRequest
0 голосов
/ 13 января 2019

У меня есть модель под названием Профиль с 2 членами posPoints и negPoints. Я пытаюсь отобразить баллы для текущего пользователя на ВК под названием MyProfileViewController. Однако, когда я печатаю profiles.posPoints, Xcode не распознает его и выдает мне эту ошибку

Значение типа '[профиль]' не имеет члена posPoints

static func show(for user: User = User.current, completion: @escaping (Profile?) -> Void) {

    let profileRef = Database.database().reference().child("profile").child(user.username)
    let ref = Database.database().reference().child("profile").child(user.username).child(profileRef.key ?? "")

    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let profile = Profile(snapshot: snapshot) else {
            return completion(nil)
        }

        completion(profile)
    })
}

import Foundation
import FirebaseDatabase.FIRDataSnapshot

class Profile {

    // MARK - Properties

    var key: String?
    let posPoints: Int
    let negPoints: Int

    init?(snapshot: DataSnapshot) {
        guard !snapshot.key.isEmpty else {return nil}
        if let dict = snapshot.value as? [String : Any]{

            let posPoints = dict["posPoints"] as? Int
            let negPoints = dict["negPoints"] as? Int

            self.key = snapshot.key
            self.posPoints = posPoints ?? 0
            self.negPoints = negPoints ?? 0
        }
        else{
            return nil
        }
    }
}

(с точки зрения загрузки MyProfileViewController)

ProfileService.show { [weak self] (profiles) in
        self?.profiles = profiles
    }
    myPointsLabel.text = profiles.posPoints
}

Просмотр базы данных Firebase

Firebase Database

1 Ответ

0 голосов
/ 13 января 2019

У вас есть следующие проблемы с вашим кодом в viewDidLoad.

1- Обновление myPointsLabel внутри completionHandler, где производится извлечение profiles.

2- Обновления пользовательского интерфейса должны выполняться в главном потоке.

3- Сначала извлеките желаемый profile из array из profiles, затем точки доступа и преобразуйте его в String.

Ваш код должен выглядеть следующим образом,

var profile: Profile?

override func viewDidLoad() {
    super.viewDidLoad()

    ProfileService.show { [weak self] (profile) in
        self?.profile = profile

        if let points = profile?.posPoints {
            DispatchQueue.main.async {
               self?.myPointsLabel.text = String(points)
            }
        }
    }
}
...