Search code examples
iosswiftfirebasefirebase-realtime-databaseuiactivityindicatorview

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


i'm not finding anything for showing the UIActivityIndicator while receiving the data from firebase realtime database. so far i've used this code but it didn't worked for me.

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

Solution

  • You need to start animating UIActivityIndicatorView outside the firebase observer callback scope and stop it once the observer returns a snapshot.

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