I have a code that loads data from firebase, the data is not loaded immediately and I want to load the data first, and then pass the data to the delegate. To do this, I used the wait construct and the synchronous loadData function
let dateUser = await loadData(phoneNumber: phoneNumber)
According to the idea, the dateUser
variable should wait until the function returns the result, but the function returns the result immediately without waiting for the data to load
Can you tell me what the error is, I think that you need to wait inside the loadData
function, but where?
Everywhere there are examples of how to use this construction for loading JSON files, but I did not find where it would be used inside the closure
here is a sample code
struct LoadData {
let db = Firestore.firestore()
var delegate: LoadDataDelegate?
func getData(phoneNumber:String){
Task.init {
let dateUser = await loadData(phoneNumber: phoneNumber)
print("Делегат получил дату - ", dateUser)
delegate!.loadData(date: dateUser)
}
}
func loadData(phoneNumber: String) async -> TimeInterval? {
var existingUser = false /// Проверка существует ли пользователь с данным номером телефона в базе
var date: TimeInterval?
db.collection("Users").getDocuments { QuerySnapshot, Error in
if let err = Error {
print("Ошибка получения данных - \(err)")
}
for document in QuerySnapshot!.documents {
if document.documentID == phoneNumber { /// Если текущий пользователь уже был зарегестрирован
existingUser = true
date = document["dateFirstLaunch"] as? TimeInterval /// Преобразуем данные из FireBase
print("это дата ",date!)
}
}
if existingUser == false { /// Если такого пользователя не было
print("New User")
db.collection("Users").document(phoneNumber).setData(["dateFirstLaunch" : NSDate().timeIntervalSince1970]) { error in
if let err = error {
print("Ошибка записи данных в обалко - \(err)")
}
}
}
}
return date
}
}
protocol LoadDataDelegate {
func loadData(date: TimeInterval?)
}
I tried to wait inside the loadData
function, but as a result, either errors come out or nothing works