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

标签 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 ,而且我不知道如何更新该值。 如何显示从数据库中获取的值?

最佳答案

这是一个有点通用的答案,因为我们只是根据从 Firebase 读取的值来更新 UI 元素。

Firebase 是异步的,值仅在 Firebase 函数之后的闭包内有效。

假设我们有一个简单的 SwiftUI 应用程序,它显示一个 Text 对象、一个用于单击以从 Firebase 加载数据的按钮,以及一个保存文本内容的 var。

struct ContentView: View {
   @State var buttonText = "Initial Button Label"

    var body: some View {
        VStack {
            Text(buttonText)

            Button(action: {
                self.readFirebase()
            }) {
                Text("Click Me!")
            }
        }
    }

    func readFirebase() {
        let ref = my_firebase_ref
        let textRef = ref.child("string_node")
        textRef.observeSingleEvent(of: .value, with: { snapshot in
            let myText = snapshot.value as? String ?? "No String"
            self.buttonText = myText
        })
    }
}

这是我的 Firebase 结构

root
   string_node: "Hello, World"

关于ios - 如何显示从数据库中获取的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59761176/

相关文章:

ios - 当手指拖动穿过按钮时触发按钮

ios - NSCollectionLayoutSupplementaryItem 显示在单元格下方

angularjs - 可编程聊天的 Twilio 推送通知失败

android - 通过改造在请求 header 中发送 Firebase ID token (不是授权 token )

macos - 使用 AudioKit 和 SwiftUI 的音频可视化工具

swift - 如何为形状添加自定义 View 修改器

ios - 如何使用 ObjectMapper 映射这个简单的 JSON

ios - 使用 UIAppearance 设置 UITableView 的背景颜色

firebase - 如何使用 Flutter 删除 Firestore 集合中的所有文档

ios - 如何使用 SwiftUI LazyVGrid 创建交错网格?