如何使用Swift(x-code)将数组添加到firebase [英] How to add an Array to firebase using Swift (x-code)

查看:66
本文介绍了如何使用Swift(x-code)将数组添加到firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑***这是我的JSON结构(忽略用于发送部分电子邮件的用户名,即用于测试)

  {
用户名:{
用户名:{
电子邮件:test@gmail.com
}
},
uid_0:{
歌曲列表:[国歌]
}
}

我正在使用swift和x代码创建一个非常简单的应用程序。基本上,用户在注册后登录他们的帐户。从那里,用户可以从乐队的唱片中选择他们喜欢的歌曲到空阵列。然后,用户可以单击将它们分割为包含所添加歌曲的表视图控制器的按钮。用户添加歌曲的方式是通过视图控制器,该控制器包含每个歌曲名称旁边都有歌曲名称和按钮的标签。当用户单击该按钮时,标签将添加到阵列中。



我希望能够将数组保存到firebase,以便每个用户都有自己喜欢的歌曲。我已经做了大量的研究,找不到任何东西来引导我朝着正确的方向前进,因为这非常简单。标签没有键,实际上只是添加到数组中的标签。



我也安装了firebase存储和数据库pod,我可以将图像上传到fire base并让用户将该图像保存到他们的特定帐户但我不能弄清楚如何为数组做同样的事情。如果有人能指引我朝着正确的方向前进,我将不胜感激!谢谢。这是我的数组代码,这样你就可以了解它是如何工作的。

  import UIKit 
import Firebase
导入FirebaseStorage
导入FirebaseAuth
导入LocalAuthentication
导入FirebaseDatabase

// var refSongs:DatabaseReference! {
//返回Database.database()。reference()

//}

var list = [String]()
class SongsViewController :UIViewController,UITableViewDelegate,UITableViewDataSource {

var ref:DatabaseReference!

覆盖func viewDidLoad(){
super.viewDidLoad()
self.ref = Database.database()。reference()

}
func tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) - > Int {
return list.count
}

@IBAction func saveSongs(_ sender:Any){
//将数组上传到firebase存储
/ / let defaults = UserDefaults.standard.set(list,forKey:KeySave)
// addSongs()

//在fire数据库中创建添加列表引用
// let addListRef = refSongs.child(Song List)。childByAutoId()

// let addList1 = list

// addListRef.setValue(addList1)

让ref = self.ref.child(uid_0)。child(歌曲列表)
//让songArray = [list] ***删除这个
ref.setValue( list)//更改为list
retriveList()
}

func retriveList(){
let ref = self.ref.child(uid_0)。 child(歌曲列表)
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)
})
}

//为数组$ b添加标签$ b func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {

let cell = UITableViewCell(style:UITableViewCellStyle.default,reuseIdentifier:cell)
cell.textLabel?.text = list [indexPath.row]
return( cell)

}

func tableView(_ tableView:UITableView,commit editingStyle:UITableViewCellEditingStyle,forRowAt indexPath:IndexPath){
if editingStyle == UITableViewCellEditingStyle.delete
{
list.remove(at:indexPath.row)
myTableView.reloadData()
}
}

覆盖func viewDidAppear(_动画:Bool){
myTableView.reloadData()
}

@IBOutlet weak var myTableView:UITableView!

覆盖func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处置可以重新创建的任何资源。
}

}

解决方案

将数组写入Firebase非常容易,Firebase可以为您完成大部分工作。



假设用户选择了三首歌曲,现在你想将它们存储在用户播放列表中

 让ref = self.ref.child(uid_0)。child( 播放列表)
让songArray = [我们和他们,回来,太阳之子]
ref.setValue(songArray)

将导致

  uid_0 
播放列表
0:我们和他们
1:回来
2:太阳之子

现在用户选择要添加到播放列表的另一首歌曲并且您想保存它。哦等等..快。 Firebase将数组视为一个对象,因此您必须读取节点,删除该节点并使用新数据重新编写节点。



现在假设用户想要查询歌曲#2的标题。也做不到! Firebase无法在数组内查询。



好的,因此您有100个用户,并希望添加一项功能,以显示其最喜欢的歌曲是太阳之子的用户。也不能这样做。



如果用户想拥有多个玩家怎么办?



基本上阵列是邪恶且有限,通常有更好的存储数据选项。



话虽如此,数组在某些情况下很有用 - 这里显示了两个选项。



以下是一个例子

  song_library 
song_0
title :我们和他们
艺术家:Pink Floyd
play_count:100
total_likes:167
song_1
title:Get Back
artist :披头士
play_count:50
total_likes:87
song_2
标题:太阳之子
艺术家:Billy Thorpe
play_count :98
total_likes:1050
song_3
标题:21世纪男人
艺术家:Billy Thorpe
play_count:36
total_likes:688
song_4
标题:Edens Gate之东
艺术家:Billy Thorpe
play_count:45
total_likes:927

uid_0
playlist_0
song_1:2
song_2:0
song_4:1
//或在这里使用数组
// 0:song_2
// 1:song_4
// 2:song_0
playlist_1
song_3:0
song_4:1

使用此结构,您可以重复使用播放列表中的歌曲,顺序由于播放列表只保留对实际歌曲数据的引用,因此可以轻松修改,删除或添加歌曲,并显着减少数据重复。



编辑:



要将该节点读回数组,这里有一个选项

  let ref = self.ref.child(uid_0)。child(playlist)
ref.observeSingleEvent(of:。value,with:{snapshot in
var mySongArray = [String]()
为snapshot.children中的孩子{
让snap = child为! DataSnapshot
让song = snap.value为! String
mySongArray.append(song)
}
print(mySongArray)
})

注意还有其他选择,但这可以保证订单。



编辑2



<这是为了帮助OP正确定义他们的类变量。

  class ViewController:UIViewController {

var ref:DatabaseReference!

覆盖func viewDidLoad(){
super.viewDidLoad()
self.ref = Database.database()。reference()


EDIT*** Here is my JSON Structure (Ignore the username to email part of it, that is for a test)

{
  "Username" : {
    "Username" : {
      "email" : "test@gmail.com"
    }
  },
  "uid_0" : {
    "Song List" : [ "The National Anthem" ]
  }
}

I am making a very simplistic app using swift and x code. Basically, the user signs into their account after they register. From there the user is able to choose their favorite songs from a band's discography into an empty array. The user is then able to click a button that segues them to a table view controller that contains the songs they added. The way the user adds songs is through a view controller that contains labels that have the song names and buttons next to each song name. When the user clicks the button the label is added to the array.

I want to be able to save the array to firebase so that each user will have their own favorite songs. I have done a decent amount of research and can not find anything to steer me in the right direction as this is incredibly simple. The labels have no keys and are literally just labels being added to an array.

I have the firebase storage and database pods installed as well and I am able to upload images to fire base and have the user save that image to their specific account but I cannot figure out how to do the same thing for an array. If somebody could steer me in the right direction is would be much appreciated! Thank you. Here is my code for the array so you can get an idea of how it works.

import UIKit
import Firebase
import FirebaseStorage
import FirebaseAuth
import LocalAuthentication
import FirebaseDatabase

//var refSongs: DatabaseReference! {
// return Database.database().reference()

//}

var list = [String]()
class SongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var ref: DatabaseReference!

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

}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return list.count
}

@IBAction func saveSongs(_ sender: Any) {
    //upload array to firebase storage
    //let defaults = UserDefaults.standard.set(list, forKey: "KeySave")
    //addSongs()

    // create add list reference in fire database
    // let addListRef = refSongs.child("Song List").childByAutoId()

    // let addList1 = list

    // addListRef.setValue(addList1)

    let ref = self.ref.child("uid_0").child("Song List")
    // let songArray = [list] *** Removed this
    ref.setValue(list) //changed to list
    retriveList()
}

func retriveList() {
    let ref = self.ref.child("uid_0").child("Song List")
    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 //!! Program crashes here!!
            mySongArray.append(song)
        }
        print(mySongArray)
    })
}

// add labels to array
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    cell.textLabel?.text = list[indexPath.row]
    return (cell)

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete
    {
        list.remove(at: indexPath.row)
        myTableView.reloadData()
    }
}

override func viewDidAppear(_ animated: Bool) {
    myTableView.reloadData()
}

@IBOutlet weak var myTableView: UITableView!

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

解决方案

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

这篇关于如何使用Swift(x-code)将数组添加到firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆