Swift Firebase完成块无限循环

时间:2016-09-09 05:07:42

标签: ios swift firebase firebase-realtime-database

我正在制作一个可以在firebase中保存很多书的应用程序。我得到一个非常奇怪的问题,其中我的应用程序将无限循环添加一本新书并尽可能快地添加相同的书。如果有经验的人可以采取任何方式来看一看,我将非常感激。

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

非常感谢,并问我是否还需要更多!

编辑: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"
                }
            }
        }
    }

然后,我添加了另一本书(索引为2),而且它不断添加无限书籍和无限增量索引(numSelling)。我不想发布JSON,因为它就像300行一样。

2 个答案:

答案 0 :(得分:3)

想通了,而不是使用observeEventType,你必须使用observeSingleEventOfType

答案 1 :(得分:-1)

请按照以下方法更改您的代码,以设置在线/离线。

// 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()])
    }

//注意:这里你必须设置字符串,所以请用字符串替换nsobject字典..可能对你有所帮助