Search code examples
swiftfirebasefirebase-realtime-databasemapkitmkmapview

Download address from firebase in mapView


Trying to upload an address from firebase and post it on mapView. But for some reason the address doesn't want to unload. The address spelled out by the string in firebase example - Moscow, Street so-and-so, house 1. What could be the reason for not loading the data?

var allAddresses: String = ""

addressRef = Database.database().reference(withPath: "Address")

addressRef.observe(.value, with: { (snapshot) in

        let value = snapshot.value as! NSDictionary

        self.allAddresses = value["address"] as? String ?? ""
    })
}

Firebase:

{
  «Address» : {
    «AddressOne» : {
      "address" : "Москва, Пресненская набережная д.8, квартира 195, подъезд 94",
    },
    "AddressTwo» : {
      "address" : "Москва, ул. Правды д.24 строение 3",
    },
    "AddressThree» : {
      "address" : "Москва,ул.Электрозаводская д.21",
    }
  }
}

Solution

  • You're attaching a value observer to /Address, which means that you get a snapshot with all data at that location. Since there are multiple child addresses, your code will need to handle those.

    The simplest way to do that is by listening for .childAdded instead of .value:

    var allAddresses: String = ""
    
    addressRef = Database.database().reference(withPath: "Address")
    
    addressRef.observe(.childAdded, with: { (snapshot) in
    
        let value = snapshot.value as! NSDictionary
    
        self.allAddresses = value["address"] as? String ?? ""
    })
    

    Now your code gets triggered with each individual address.

    You can also stick to observing .value and then loop over the results in the snapshot:

    var allAddresses: String = ""
    
    addressRef = Database.database().reference(withPath: "Address")
    
    addressRef.observe(.value, with: { (snapshot) in
        for address in snapshot.children.allObjects as [FIRDataSnapshot] {
            let value = address.value as! NSDictionary
    
            self.allAddresses = value["address"] as? String ?? ""
        })
    })