简体   繁体   中英

Swift Firebase Completion Block Infinite Loop

I am making an app that holds many books in firebase. I am getting a very strange problem wherein my application will infinite loop when adding a new book and keep adding the same book as fast as it can. If there would be any way that a more experienced person could take a look, I would be very grateful.

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

Thanks a ton and ask me if you need anything more!

EDIT: JSON BEFORE BELOW

   {
        "colorado" : {
            "numBuying" : 0,
            "numSelling" : 0,
        "users" : {
                "2nU0jp4ITjgQ6ElSQWc7t5qj62t1" : {
                    "email" : "vhegde@colorado.edu"
                }
            }
        },
        "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" : "vhegde@creek.edu"
                }
            }
        }
    }

Then, I add another book (index of 2) and rather it keeps adding infinite books and infinitely increments index (numSelling). I don't want to post that JSON as it is like 300 lines long.

弄清楚了,而不是使用observeEventType,必须使用observeSingleEventOfType

Please change Your code as i have implemented in below method to set online/offline.

// MARK: - User Online/Offline

func setUserOnlineOffline(userId: String!, isOnline: Bool!) {
        Let ref = FIRDatabase.database().reference().child(FIRPATH_USER_USERID_DETAILS(userId))

        if isOnline == true {
            ref.updateChildValues(["last_seen": "Online"])
        } else {
            ref.updateChildValues(["last_seen": FIRServerValue.timestamp()])
        }

        ref.onDisconnectUpdateChildValues(["last_seen": FIRServerValue.timestamp()])
    }

//note: here you have to set string, so please replace dictionary of nsobject with string .. might be helpful to you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM