How can I get the result in the UI (@escaping , completion)

Viewed 61

I've got an func that read data from DB. this func with @escaping. how should I declare a var in UI, to get my result. thanks

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)
    }
}
2 Answers

Like this:

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

With this code in works great. Thanks everyone for help)

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)
    }   
}

}
Related