2
votes

I'm trying to load an image stored in a Firebase server. I was checking other answers but I couldn't find why I'm getting a nil after being able to print the right String value:

In my application I have the following data structure:

Structure

And here the code I'm using to load it (The nil value is the one shown on the comment)

let profileDetailsRef = self.ref.childByAppendingPath("users/" + sessionUserID + "/details")

    profileDetailsRef.observeEventType(.Value, withBlock: { snapshot in 
        self.txtUsername.text = sessionUserID
        self.txtDisplayName.text = snapshot.value.objectForKey("nameToDisplay") as? String

        let base64EncodedString = snapshot.value.objectForKey("userImage")! as! String

        print(base64EncodedString) //Here it's printing well because I get the same value as shows in the dasboard so it finds it

        //But the value "decodedData" here below is returning **nil**
        let decodedData = NSData(base64EncodedString: base64EncodedString as! String, options: NSDataBase64DecodingOptions())

        let decodedImage = UIImage(data: decodedData!)!

        self.imageUserImage.image = decodedImage

        }, withCancelBlock: { error in
            print(error.description)
    })

Thanks!

1

1 Answers

3
votes

It might be a lot easier to use an image hosting API like Cloudinary and simply store the URL in Firebase.

That said, the problem is likely that your encoding and decoding options don't match. Try just providing [] in each options field. For example, to encode:

let image = [#Image(imageLiteral: "icon.png")#] // your UIImage
let imageData = UIImagePNGRepresentation(image)! // or however you store your image
let base64EncodedString = imageData.base64EncodedStringWithOptions([])

And to decode:

if let decodedData = NSData(base64EncodedString: base64EncodedString, options: []),
   let decodedImage = UIImage(data: decodedData) {
    // do something with decodedImage
}

If that doesn't work, Firebase may be truncating your image because the string length exceeds their limits.

This approach isn't a great way to store and load images — you miss out on HTTP caching, content types, server-side optimizations, etc. — so I'd try to avoid if you can.