我有一些信息要发送到Firebase。问题是我想发送数据,但我也必须先从那里提取数据。我得到的数据是基于用户输入的。
我已经对Firebase进行了几个嵌套的异步调用。我不仅需要等待调用完成,以确保数据已设置,而且我不希望让用户在不必要的情况下等待,因为他们可以离开场景,并且可以在后台任务中提取和更改数据。
我正在考虑在触发NSNotification后使用performSegueWithIdentifierobservernotification将位于viewWillDisappear内部。
这样做安全吗?如果不安全,最好的办法是什么?
代码:

var ref: FIRDatabaseReference!
let uid = FIRAuth.auth()?.currentUser?.uid
let activityIndicator = UIActivityIndicatorView()

override func viewDidLoad() {
     super.viewDidLoad()
     self.ref = FIRDatabase.database().reference().child(self.uid!)
}

override func viewWillDisappear(animated: Bool) {
     super.viewWillDisappear(animated)
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(fetchSomeValueFromFBThenUpdateAndResendAnotherValue), name: "FbFetchAndSend", object: nil)
}

@IBAction func buttonPressed(sender: UIButton) {
    activityIndicator.startAnimating()
    levelTwoRef //send levelTwo data to FB run 1st callback
         scoreRef   //send score data to FB run 2nd callback
            powerRef //send power data to FB run 3rd  callback
               lifeRef //send life data to FB run Last callback for dispatch_async...

                   dispatch_async(dispatch_get_main_queue()){
                      activityIndicator.stopAnimating()
                      performSegueWithIdentifier....
                      //Notifier fires after performSegue???
                      NSNotificationCenter.defaultCenter().postNotificationName("FbFetchAndSend", object: nil)
                  }
 }

func fetchSomeValueFromFBThenUpdateAndResendAnotherValue(){

    let paymentRef = ref.child("paymentNode")
    paymentRef?.observeSingleEventOfType(.Value, withBlock: {
       (snapshot) in
       if snapshot.exists(){
           if let dict = snapshot.value as? [String:AnyObject]{
           let paymentAmount = dict["paymentAmount"] as? String

           let updatePayment = [String:AnyObject]()
           updatePayment.updateValue(paymentAmount, forKey: "paymentMade")

           let updateRef = self.ref.child("updatedNode")
           updateRef?.updateChildValues(updatePayments)
}

最佳答案

您正在视图中添加的观察者将消失,因此不会被激发,因为它在执行segue时不存在。
在viewDidLoad中添加观察者,它就可以工作了。
但是,如果只想在视图消失时调用fetchSomeValueFromFBThenUpdateAndResendAnotherValue(),则不需要观察者。
只需调用viewwill上的方法就会像这样消失-

override func viewWillDisappear(animated: Bool)
{
    super.viewWillDisappear(animated)
    fetchSomeValueFromFBThenUpdateAndResendAnotherValue()
}

10-06 13:11
查看更多