Leo
Leo

Reputation: 1

Download Images from Firebase/Storage with regards to "Last modified"

I want to download Images from my Firebase/Storage with regards to when they were uploaded. Meaning, that the last uploaded picture will be the first one in my newsfeed (somewhat like instagram).

How could I write such a code? I don't really know where to start, do I make an ImageArray, or do I have to define every UIImageView? I can not find help provided by Firebase regarding this topic.

Help is appreciated. Thank you !

Upvotes: 0

Views: 1894

Answers (1)

Mike McDonald
Mike McDonald

Reputation: 15953

We highly recommend using Firebase Storage and the Firebase Realtime Database together to accomplish this. Here's a full example of something similar:

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

At this point, you can simply use the images in picArray to display them in a tableView. You can even use a Firebase Database query to query ordered by a timestamp of the file or other information (you'll want to write that when you write the URL to the database).

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.

Upvotes: 2

Related Questions