ezera.olsen
ezera.olsen

Reputation: 45

Could not cast value of type 'FIRDatabaseReference' (0x108f4d170) to 'NSString' (0x10a4f24a8)

I have a database reference that I want to change to a String and then to a URL type.

let database = Database.database().reference().child("users/profile/\(uid!)/pathToImage")

let string = database as! String  // **Code Crashes here
let url = URL (string: string)!

func setImage() {
  ImageService.downloadImage(withURL: url) { image in
    self.currentProfileImage.image = image
   }
}

setImage()

Upvotes: 0

Views: 62

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317392

It sounds like you might be confused about how the Realtime Database SDK works. If you have a database reference, and you want the value of that location of the database, it's not going to work to simply convert that reference to a string. You have to query the database at that location, use a callback to receive the data, then get the string out of the snapshot that was delivered to the callback.

I suggest going over the documentation for how to perform database queries in order to understand how it works. In particular, pay attention to the section called read data once. Your code will look more like this:

let ref = ref.child("path/to/string")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
  let value = snapshot.value as? String
  // use the value here
  }) { (error) in
    print(error.localizedDescription)
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

This

let database = Database.database().reference().child("users/profile/\(did!)/pathToImage")

isn't a type of a direct url string , it's a refrence to your image , you need to single listen to it

database.observeSingleEvent(of: .value, with: { (snapshot) in 
  let str = snapshot.value as! String
  print(str)
})

Upvotes: 1

Related Questions