How to get a list of all files in Cloud Storage in a Firebase app?

后端 未结 19 1005
傲寒
傲寒 2020-11-21 11:25

I\'m working on uploading images, everything works great, but I have 100 pictures and I would like to show all of them in my View, as I get the complete list of

19条回答
  •  甜味超标
    2020-11-21 11:57

    Since there's no language listed, I'll answer this in Swift. We highly recommend using Firebase Storage and the Firebase Realtime Database together to accomplish lists of downloads:

    Shared:

    // Firebase services
    var database: FIRDatabase!
    var storage: FIRStorage!
    ...
    // Initialize Database, Auth, Storage
    database = FIRDatabase.database()
    storage = FIRStorage.storage()
    ...
    // Initialize an array for your pictures
    var picArray: [UIImage]()
    

    Upload:

    let fileData = NSData() // get data...
    let storageRef = storage.reference().child("myFiles/myFile")
    storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
      // When the image has successfully uploaded, we get it's download URL
      let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
      // Write the download URL to the Realtime Database
      let dbRef = database.reference().child("myFiles/myFile")
      dbRef.setValue(downloadURL)
    }
    

    Download:

    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)
      })
    })
    

    For more information, see Zero to App: Develop with Firebase, and it's associated source code, for a practical example of how to do this.

提交回复
热议问题