Firebaseを使用してリアルタイムデータベースからデータを取得できるように関数を実行しようとしていますが、関数を実行するたびに; 私の関数のobserverSingleEvent部分は実行されません.printステートメントを挿入しようとしましたが、実行されておらず、フィールドが変数に読み取られていません.
func checkIfNewDay() -> Bool {
print(self.currDate)
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
print("outside function")
ref.child("user").child(userID!).child("dates").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
print("inside function")
let value = snapshot.value as? NSDictionary
print("just to make sure its going inside the function. Delete after")
self.lastDate = value?["lastSaveDate"] as? String ?? "Date Invalid"
self.newLastDate = String(self.lastDate)
if self.newLastDate != "Date Invalid" {
print(self.lastDate)
} else {
print("Error, date not able to be recieved from the database")
self.catchGetDateError = true
self.saveCurrentDate()
}
})
if (!self.catchGetDateError) {
print(self.newLastDate, "newLastDate")
print(self.currentDate, "currentDate")
if (self.newLastDate == self.currentDate) {
print("Day has not moved on.")
return false
} else {
print("Day has moved on!")
return true
}
}
return true
}
非常に長い関数で申し訳ありません - 書くのはかなり奇妙なものでした。
コメントから、私は理解したと思います、あなたは何を望んでいますか。
同期のようにこの結果を得るには、エスケープを実装する必要があります。このような:
func checkIfNewDay(completion: @escaping (_ isNew: Bool) -> Void) {
print(self.currDate)
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
print("outside function")
ref.child("user").child(userID!).child("dates").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
print("inside function")
let value = snapshot.value as? NSDictionary
print("just to make sure its going inside the function. Delete after")
self.lastDate = value?["lastSaveDate"] as? String ?? "Date Invalid"
self.newLastDate = String(self.lastDate)
if self.newLastDate != "Date Invalid" {
print(self.lastDate)
if (self.newLastDate == self.currentDate) {
print("Day has not moved on.")
completion(false)
} else {
print("Day has moved on!")
completion(true)
}
} else {
print("Error, date not able to be recieved from the database")
self.catchGetDateError = true
self.saveCurrentDate()
completion(false)
}
})
}
これで、func を使用できます。
checkIfNewDay(completion: { isNew in
// do whatever you want. isNew will have info, that you need.
})
.observe 関数は非同期で動作するため、これが必要です。考え方は理解できるはずです。
それが役に立てば幸い。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加