如何显示从数据库中获取的值?

时间:2020-01-15 23:51:27

标签: ios firebase swiftui

我正在使用SwiftUI开发iOS应用程序,但无法显示从数据库中获取的数据。

代码

import SwiftUI
import Firebase
import FirebaseDatabase

var ref = Database.database().reference()

class Observe {
    static func currentSingleEventObserve(completion: @escaping ((String?) -> ())) {
        let path = "supersonic/current"
        let ref = Database.database().reference().child(path)
        _ = ref.observeSingleEvent(of: .value, with: { snapshot in
            let temp = (snapshot.value! as AnyObject).description
            completion(temp)
        })
    }
}

struct CurrentDistance: View {
    var value: NSDictionary?
    var refHandle: UInt = 0

    @State var distance: String

    init() {
        Observe.currentSingleEventObserve(completion: { temp in
            self.distance = temp    // I want to mutate self.distance here
        })
    }

    var body: some View {
        VStack {
            Text("Distance")
            Text(self.distance)
        }
    }
}

struct CurrentDistance_Previews: PreviewProvider {
    static var previews: some View {
        CurrentDistance()
    }
}

数据库

|-supersonic
    |- current: 30

问题

我想在初始化器中对self.distance进行突变。尝试在闭包中更改self.distance时出现错误Escaping closure captures mutating 'self' parameter,并且我不知道如何更新该值。 如何显示从数据库中获取的值?

0 个答案:

没有答案