3

I'm trying to load data from the firebase. I successfully load the data like usename and email, but somehow it fails to load the image. I'm attaching my code which I have used to load the data from firebase. Please help. thank you.

code :

import UIKit
import FirebaseDatabase
import  Firebase

class ProfileVC: UIViewController {


@IBOutlet weak var currentphoto: UIImageView!

@IBOutlet weak var usernameLabel: UILabel!

@IBOutlet weak var BioOrEmailLabel: UILabel!

var databasereff : DatabaseReference!


override func viewDidLoad() {
    super.viewDidLoad()

    databasereff = Database.database().reference()
    if let userid = Auth.auth().currentUser?.uid
    {
        databasereff.child("users").child(userid).observeSingleEvent(of: .value, with: { (snapshot) in
            let dict = snapshot.value as? [String:Any]
            let username = dict?["username"] as? String
            let email = dict?["email"] as? String
            if let photourl = dict?["profileimageUrl"] as? String
            {
                let url = URL(string: photourl)
                URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                    if error != nil{
                            print(error?.localizedDescription)
                        return
                    }
                    OperationQueue.main.addOperation  {
                        self.currentphoto.image = UIImage(data: data!)
                    }
                }).resume()
            }
            self.usernameLabel.text = username
            self.BioOrEmailLabel.text = email
        })
        {
            (error) in
            print(error.localizedDescription)
        }
    }

    // Do any additional setup after loading the view.
}

 }
KENdi
  • 7,576
  • 2
  • 16
  • 31
deltami
  • 303
  • 2
  • 17

1 Answers1

0

You need to create FIRStorage reference to retrieve files from Firebase Data Base.

First:

import FirebaseStorage

Second take a storage reference:

var storage: FIRStorage!

Then Initialize it

storage = FIRStorage.storage()

Now:

let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
  // Get download URL from snapshot
  let downloadURL = snapshot.value() as! String
  // Create a storage reference from the URL
  let storageRef = storage.referenceFromURL(downloadURL)
  // Download the data, assuming a max size of 1MB (you can change this as necessary)
  storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
    // Create a UIImage, add it to the array
    let pic = UIImage(data: data)
    picArray.append(pic)
  })
})

In your case path is different so just change the path and Cheers!

Reference: from here

Anurag Sharma
  • 4,276
  • 2
  • 28
  • 44