Adding Firebase Data to an Array in iOS Swift

How to create an array in firebase database in iOS swift

use childByAutoId()

Database.database().reference().child("arrayKey").childByAutoId().setValue("Value") }

Can you append a string to a Firebase array with swift

Firestore has a special documented operation to append a single item to the end of an array using FieldValue.arrayUnion():

let washingtonRef = db.collection("cities").document("DC")

// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayUnion(["greater_virginia"])
])

If you want make any changes to an array other than add or remove a single item, you will have to read the array, modify it, then write it back.

Append Firebase data to an array in Swift

Try something like this:

var imageArray = []

func appendData(){
let ref = FIRDatabase.database().reference().child("users")

ref.observeEventType(.Value, withBlock: { snapshot in
var tempImageArray = []

for user in snapshot.children {
userUrl = user.value?["profile_image_1"] as? String
self.imageArray.insert(userUrl, atIndex: 0)
tempImageArray.append(broadcastItem)
}

self.imageArray = tempImageArray
})
}

edit: I updated the code, please try this.

Append Firebase data to an array in Swift ios

func sen(){
var rootRef: FIRDatabaseReference!
var refHandle: UInt!
var haneRef: FIRDatabaseReference!
var numbersArray = [Int] ()

rootRef = FIRDatabase.database().reference()
haneRef = rootRef.child("SES2014")

let queryCount = 4
haneRef.queryOrderedByChild("lg_Et harcaması").queryLimitedToLast(queryCount).observeEventType(.ChildAdded, withBlock: { (snapshot) in
let hhtype = snapshot.value!["HHtype"] as? Int
numbersArray.append(hhtype!)
queryCount -= 1
if queryCount <= 0 {
print(numbersArray)
}

})

}

How to add an array to Firebase Firestore Swift

You must pass an array to Firestore to update an array property. What you're doing is passing an element of an array. The remove(at:) method, when used like this:

let removedElement = someArray.remove(at: someIndex)

will remove the element but return the value of that removed element; it doesn't return the updated array. You must first remove the element and then get the truncated array:

someArray.remove(at: someIndex)
let updated = someArray

Therefore, first remove, then update:

data[0].upvotes!.remove(at: data[0].upvotes!.firstIndex(of: MainView.username ?? "Anonymous")! // first remove
db.collection("forum").document(data[0].id!).setData([
"upvotes": data[0].upvotes!) // then pass
])

However, I'd recommend reformatting the code because it doesn't read very well, IMO, and there is too much force unwrapping for my taste.

How to add an Array to firebase using Swift (Xcode)

Writing an array to Firebase is incredibly easy and Firebase does most of the work for you.

Suppose the user selects three songs and now you want to store them in the users playlist

let ref = self.ref.child("uid_0").child("playlist")
let songArray = ["Us and Them", "Get Back", "Children of the Sun"]
ref.setValue(songArray)

will result in

uid_0
playlist
0: "Us and Them"
1: "Get Back"
2: "Children of the Sun"

Now the user selects another song to add to the playlist and you want to save it. Oh wait.. snap. Firebase treats the array as one object so you have to read the node, delete that node and re-write the node with the new data.

Now suppose the user wants to query for the title of song #2. Can't do that either! Firebase Can't query inside an array.

Ok, so you have 100 users and want to add a feature to show the users whose favorite song is Children of the Sun. Can't do that either.

What if the user wants to have multiple playists?

Basically Arrays Are Evil and limited and there are usually much better options for storing data.

That being said, arrays can be useful in some cases - two options are shown here.

Here's an example

song_library
song_0
title: "Us and Them"
artist: "Pink Floyd"
play_count: 100
total_likes: 167
song_1
title: "Get Back"
artist: "Beatles"
play_count: 50
total_likes: 87
song_2
title: "Children of the Sun"
artist: "Billy Thorpe"
play_count: 98
total_likes: 1050
song_3
title: "21st Century Man"
artist: "Billy Thorpe"
play_count: 36
total_likes: 688
song_4
title: "East of Edens Gate"
artist: "Billy Thorpe"
play_count: 45
total_likes: 927

uid_0
playlist_0
song_1: 2
song_2: 0
song_4: 1
//or use an array here
//0: song_2
//1: song_4
//2: song_0
playlist_1
song_3: 0
song_4: 1

With this structure, you can re-use songs in playlists, the sequence can be easily modified, songs and be removed or added and data duplication is significantly reduced as the playlists just keep references to the actual song data.

EDIT:

To read that node back into an array, here's one option

let ref = self.ref.child("uid_0").child("playlist")
ref.observeSingleEvent(of: .value, with: { snapshot in
var mySongArray = [String]()
for child in snapshot.children {
let snap = child as! DataSnapshot
let song = snap.value as! String
mySongArray.append(song)
}
print(mySongArray)
})

Note there are other options but this guarantees the order.

Edit 2

This is to help the OP define their class vars correctly.

class ViewController: UIViewController {

var ref: DatabaseReference!

override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()

How to put an array into Firebase Swift

Your code is close but let's take a look at what it's doing. Firebase strucures are always key: value pairs (e.g. think Dictionary) so this is valid

name: "Leeroy"

wheras this is not

"TestNode"

as you can see TestNode is not a key: value pair.

["TestNode", "Hello", "Test123"]

is also not valid as it's now an array of strings - not key: value pairs.

This is valid a valid key: value pair

user_0
name: "Leeroy"

because user_0 is the key and name: "Leeroy" is the value, which is also a key: value pair.

The reason your code isn't working as it's trying to write a single string, TestNode to Firebase without it being in a key: value format. So fix it by making the data a key: value pair (Dictionary) instead of a single string (on in your case a single string stored in an array)

let dict = [
"name": "Leeroy",
"food": "pizza"]

let testRef = self.ref.child("TestNode")
testRef.updateChildValues(dict) { (error, value) in
if error != nil {
return
} else {
}
}

This will result in the following structure being written to Firebase

TestNode
name: "Leeroy",
food: "pizza"

Firebase needs to know where you want data stored; when you tell it to add or update the pizza value in the TestNode/food node, it knows specifically where you want the data written.

An array of strings should not be directly written to Firebase as it will be just that, an array. Each element of the array would generally be associated with a node (key) to make each element a key: value pair. This is good form, makes your Firebase queryable and more maintainable.

While it may be tempting to use arrays in Firebase (because it can be done) - don't. It's not a concept that works well in NoSQL databases. See Don't Use Arrays and also this post and maybe this one as well for further reading.

Read Data from Firebase and Save Into an Array (Swift)

I figured it out after sleeping on it. Posting here to make it easier for the next person to figure out.

 // Class variables
var ref = Firebase(url: "https://<MYFIREBASEURL>")
var titlesArray = [String]()

// Under viewDidLoad

// "events" is the root, and "title" is the key for the data I wanted to build an array with.
let titleRef = self.ref.childByAppendingPath("events")
titleRef.queryOrderedByChild("title").observeEventType(.ChildAdded, withBlock: { snapshot in

if let title = snapshot.value["title"] as? String {
self.titlesArray.append(title)

// Double-check that the correct data is being pulled by printing to the console.
print("\(self.titlesArray)")

// async download so need to reload the table that this data feeds into.
self.tableView.reloadData()
}
})

How to Append Filter Data on Array from Firebase in Swift

   let ref = Database.database().reference(withPath: "Messages")
let query = ref.queryOrdered(byChild: "VideoID").queryEqual(toValue: "12345").observe(.value, with: { (snapshot) in
print(snapshot)

for (childSnapshotId, childSnapshotValue) in snapshot {
if let dataListDict = childSnapshotValue as? [String: AnyObject] {
//Init you newModel with the dataListDict here
let newModel = DatabaseList(dict: dataListDict)
print(childSnapshot)
self.childrenList.append(newModel)
}
}

DispatchQueue.main.async {
self.tableView.reloadData()
}
})

class DatabaseList : NSObject {
var messageBody : String?
var name : String?
var videoID : String?
init(dict: [String: AnyObject]) {
messageBody = dict["MessageBody"]
name = dict["Name"]
videoID = dict["videoID"]
}
}


Related Topics



Leave a reply



Submit