当应用程序从 Firebase 实时数据库接收数据时如何显示 UIActivityIndi​​cator

how can i show UIActivityIndicator while the app receive data from Firebase Realtime database

在从 firebase 实时数据库接收数据时,我没有找到任何用于显示 UIActivityIndi​​cator 的内容。到目前为止,我已经使用了这段代码,但它对我不起作用。

//Check if the internet is connected or not
    let connectedRef = Database.database().reference(withPath: ".info/connected")
    connectedRef.observe(.value, with: { snapshot in

        let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        myActivityIndicator.center = self.view.center

        if snapshot.value as? Bool ?? false {
            print("Connected")
            myActivityIndicator.stopAnimating()
            myActivityIndicator.isHidden = false               
        }
        else {
            myActivityIndicator.startAnimating()
            print("Not connected")
        }

       testView.addSubview(myActivityIndicator)
    })

您需要在 firebase 观察者回调范围之外开始为 UIActivityIndi​​catorView 设置动画,并在观察者 returns 快照后停止它。

var activityIndicator: UIActivityIndicatorView! 

override func viewDidLoad() {
  var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: 
   UIActivityIndicatorViewStyle.Gray) 
   activityIndicator.hidesWhenStopped = true; 
   activityIndicator.isHidden = true 
   activityIndicator.center = view.center;
   addSubview(myActivityIndicator)
   super.viewDidLoad()
}

func firebaseObserver() {
  // Show indicator 
  activityIndicator.isHidden = false
  activityIndicator.startAnimating()

  // Firebase network observer 
  let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in

   // Stop and hide indicator
   self.activityIndicator.stopAnimating()
   self.activityIndicator.isHidden = true

   // Proceed with other operations.
     })
}