func observeActiveTrackingState() -> String{
let pathToObserveState = databaseRef.child("locationState").child("\(userID!)")
pathToObserveState.observeSingleEvent(of: .value, with: { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
print("Snapshot Returned (ObserveActiveTrackingState) = \(snapshotValue?["state"] as! String)")
let currentState = snapshotValue?["state"] as! String
return currentState //*****GIVES ME AN ERROR*****
})
//IF I PUT THE RETURN HERE HOW DO I CALL THE CURRENTSTATE VARIABLE
}
我有一个名为" observeActiveTrackingState"应该返回一个字符串,通常在添加一个返回时它会返回我想要的字符串变量,但是因为我需要将return语句置于
之下pathToObserveState.observeSingleEvent(of: .value, with: { (snapshot) in
})
它返回一个错误,并说它需要在firebase的完成块之外发生。如何修复此代码,以便在调用函数时获取我想要的变量
答案 0 :(得分:0)
你应该使用一个闭包来接受你想要返回的类型的参数:
./bin/spark-shell --master spark://slaver1:7077 --executor-memory 500m
//
你可以创建一个全局闭包变量并调用它:
func observeActiveTrackingState(_ completion: (String) -> ()) {
let pathToObserveState = databaseRef.child("locationState").child("\(userID!)")
pathToObserveState.observeSingleEvent(of: .value, with: { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
print("Snapshot Returned (ObserveActiveTrackingState) = \(snapshotValue?["state"] as! String)")
let currentState = snapshotValue?["state"] as! String
completion(currentState)
})
}