简体   繁体   English

Swift Firebase完成区块无限循环

[英]Swift Firebase Completion Block Infinite Loop

I am making an app that holds many books in firebase. 我正在制作一个可以在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 编辑:下面的JSON

   {
        "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). 然后,我添加另一本书(索引为2),而是继续添加无限书并无限增加索引(numSelling)。 I don't want to post that JSON as it is like 300 lines long. 我不想发布该JSON,因为它的长度约为300行。

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

Please change Your code as i have implemented in below method to set online/offline. 请按照我在以下方法中实现的方式更改您的代码以设置在线/离线。

// MARK: - User Online/Offline // MARK:-在线/离线用户

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 //注意:这里必须设置字符串,所以请用字符串..替换nsobject的字典,这可能对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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