私はfirebaseに多くの本を収めたアプリを作っています。私は非常に奇妙な問題を抱えています。新しい本を追加するときにアプリケーションが無限ループし、できるだけ早く同じ本を追加し続けます。より経験豊富な人が見ることができる方法があれば、私はとても感謝しています。Swift Firebase Completion Block無限ループ
@IBAction func userHasBook(sender: AnyObject) { // Called after filling a new book form
let email = FIRAuth.auth()?.currentUser?.email!
let school = email!.substringWithRange(Range(email!.characters.indexOf("@")!.advancedBy(1) ..< email!.characters.indexOf(".")!)) // for db organization
//A few lines here that ensure that the fields are filled correctly (clutter so i didn't add them)
ref.child(school).observeEventType(.Value, withBlock: { (snapshot) in
self.bookIndex = snapshot.value!["numSelling"] as! Int
self.addSellingBook(); // we now know it is done finding the value, right?
}) { (error) in
print(error.localizedDescription)
}
}
func addSellingBook(){
let bookRef = self.ref.child(school).child("selling").child(Int(self.bookIndex).description)
let book : [NSObject : AnyObject] = ["uid": (FIRAuth.auth()?.currentUser?.uid)!,
"title": self.titleField.text!,
"authors": self.authorsField.text!,
"edition": self.editionField.text!,
"price": self.priceField.text!,
"isbn" : self.isbn] // this is the data that is added infinitely many times
bookRef.updateChildValues(book, withCompletionBlock: { (NSError, FIRDatabaseReference) in //update the book in the db
let newIndex = self.bookIndex + 1
self.ref.child(self.school).child("numSelling").setValue(newIndex, withCompletionBlock: { (NSError, FIRDatabaseReference) in // after that update the index
self.performSegueWithIdentifier("backToMain", sender: nil) // and after that go back to main
})
})
感謝トン、あなたはより多くの何が必要な場合は私に尋ねます!
EDIT:JSON前に、以下の
{
"colorado" : {
"numBuying" : 0,
"numSelling" : 0,
"users" : {
"2nU0jp4ITjgQ6ElSQWc7t5qj62t1" : {
"email" : "[email protected]"
}
}
},
"creek" : {
"numBuying" : 0,
"numSelling" : 2,
"selling" : [ {
"authors" : "A. S. A. Harrison",
"edition" : "Only Edition",
"isbn" : "1101608064",
"price" : "5.00",
"title" : "The Silent Wife",
"uid" : "eJvdVx3J8EYZPH3mlbYLBcPDkD12"
}, {
"authors" : "Jamie McGuire",
"edition" : "Only Edition",
"isbn" : "1476712050",
"price" : "5.00",
"title" : "Beautiful Disaster",
"uid" : "eJvdVx3J8EYZPH3mlbYLBcPDkD12"
} ],
"users" : {
"eJvdVx3J8EYZPH3mlbYLBcPDkD12" : {
"email" : "[email protected]"
}
}
}
}
その後、私は別の本(2のインデックス)を追加し、むしろそれは無限の本を追加し続け、無限にインデックス(numSelling)をインクリメントします。私はJSONを300行ほどのように投稿したくありません。
'bookRef.updateChildValues(これはあなたのDBノードにこのブックの詳細を追加しようとしていますか? JSON tree.Andは無限ループが始まる場所ですか? – Dravidian
データベースにデータがある場合、 'observeEventType'を呼び出すことによってそのデータを取得していると思われ、完了すると' addSellingBook'が実行され、それがサークルになります。 –