Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect internet connection with Firebase Database using Swift3?

Can any one help me to detect internet connection with Firebase Database using Swift 3? I am using this function to download data from database.

  func loadData(){


    Ref=FIRDatabase.database().reference()

    Handle = Ref?.child("Posts").queryOrdered(byChild: "Des").queryEqual(toValue: "11").observe(.childAdded ,with: { (snapshot) in

        if  let post = snapshot.value as? [String : AnyObject] {

            let img = Posts()

            img.setValuesForKeys(post)

            self.myarray.append(img)

                self.tableView.reloadData()

        }else {


        }

    })

}
like image 645
Zaid Mustafa Avatar asked Jan 15 '17 12:01

Zaid Mustafa


1 Answers

If you want to detect whether your app has a connection to the Firebase Database backend, you can listen for /.info/connected. This example from the Firebase documentation on detecting connection state should do the trick:

let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
connectedRef.observeEventType(.Value, withBlock: { snapshot in
    if let connected = snapshot.value as? Bool where connected {
        print("Connected")
    } else {
        print("Not connected")
    }
})

Swift 3.1

let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
    connectedRef.observe(.value, with: { snapshot in
    if let connected = snapshot.value as? Bool, connected {
        print("Connected")
    } else {
        print("Not connected")
    }
})

Objective C

FIRDatabaseReference *connectedRef = [[FIRDatabase database] referenceWithPath:@".info/connected"];
    [connectedRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
   if([snapshot.value boolValue]) {
    NSLog(@"connected");
  } else {
    NSLog(@"not connected");
  }
}];
like image 184
Frank van Puffelen Avatar answered Nov 16 '22 00:11

Frank van Puffelen