【问题标题】:How can I get the result in the UI (@escaping , completion)如何在 UI 中获得结果(@escaping,完成)
【发布时间】:2020-10-20 21:07:30
【问题描述】:

我有一个从数据库读取数据的函数。这个函数带有@escaping。我应该如何在 UI 中声明一个 var 以获得我的结果。谢谢

class GetGarbageInfo {

    func getInfo(path: String, completion: @escaping (String) -> Void) {
        var result = ""
        
        let rootReference = Database.database().reference()
        let garbageReference = rootReference.child("GarbageInformation").child(path).child("body")
        
        garbageReference.observeSingleEvent(of: .value) { (DataSnapshot) in
            result = DataSnapshot.value as? String ?? "0"
        }
        completion(result)
    }
}

【问题讨论】:

    标签: swift firebase-realtime-database swiftui


    【解决方案1】:

    像这样:

    getInfo(path: yourPath) { resultString in 
       /// resultString is the result!
    }
    

    【讨论】:

    • 我在 UI 中遇到了这个错误:Type '()' cannot conform to 'View';只有结构/枚举/类类型可以符合协议
    • 等等,你是在 SwiftUI 中调用这个函数吗?在哪里?它在按钮的action 内吗?
    • 试试this
    • 我尝试过,但它不起作用。但感谢您的支持)
    • @LeonidSpiridonov 这里是gist,它应该可以工作
    【解决方案2】:

    使用此代码效果很好。谢谢大家的帮助)

    struct ContentView: View {
        
        let garbageInfo = GetGarbageInfo() 
        
        @State var result = ""
        var body: some View {
            VStack {
                Text(result)
            }.onAppear {
                garbageInfo.getInfo(path: yourPath) {
                    result = resultString
                }
            }
        }
    }
    
    
    
    
    class GetGarbageInfo {
    
    func getInfo(path: String, completion: @escaping (String) -> Void) {
        var result = ""
        let rootReference = Database.database().reference()
        let garbageReference = rootReference.child("GarbageInformation").child(realPath).child("body")
        
        garbageReference.observeSingleEvent(of: .value) { (DataSnapshot) in
            result = DataSnapshot.value as? String ?? "0"
            completion(result)
        }   
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-06
      • 1970-01-01
      • 2021-12-26
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2019-07-25
      相关资源
      最近更新 更多