udin
udin

Reputation: 65

How to convert Firebase result to List in SwiftUI

I wanted to make a list in swiftui from firebase data. So here's my UI enter image description here

I've already make a data for that username "mike_one", and it's perfectly working, this is my xcode result

{
IC2ol5bimucKu2d89u2YBz0Bqot2 =     {
    name = mike;
    photo = "https://firebasestorage.googleapis.com/v0/b/instagram-ios-1ed09.appspot.com/o/photo%2Fa2.jpg?alt=media&token=9b6c58f1-eedc-4190-bc63-3f3325c84d77";
    username = "mike_one";
};}

And this is my database enter image description here

So what i'm asking right now is, How to make the result of the database to be a model? so I can use it as a list.

Please help me. I appreciate your answer!

Upvotes: 0

Views: 473

Answers (1)

Jay
Jay

Reputation: 35657

Strictly speaking, it would not be possible to convert textual firebase data to a List object. A SwiftUI List is defined as

A container that presents rows of data arranged in a single column

in other words it's a UI element, not a data element.

That being said a List is often backed by an Array or other data storage element. So you'll read Firebase data and store that in an array. Then that array backs your UI List object.

In this case, I would suggest creating a UserClass to hold the Firebase data

class UserClass {
   var name = ""
   var photoUrl = ""
   var username = ""
}

and then array to store your users in

var userArray = [UserClass]()

then as data is read from Firebase, create the user objects and populate the array. Your Firebase code wasn't included so in brief

firebase.observe.... { snapshot in
   let user = UserClass()
   ...populate user properites from the snapshot
   self.userArray.append(user)
}

Then in your view, access the array elements to show them in the List object

struct ContentView: View {
    var body: some View {
        List(userArray) { user in
         //do something with each user object
         // like Text(user.username)
        }
    }
}

Upvotes: 1

Related Questions