LoginSignup
14
15

More than 5 years have passed since last update.

swiftでfirebaseの追加、更新、削除

Posted at

前提

class ViewController: UIViewController {

    // インスタンス変数
    var DBRef:FIRDatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()

        //インスタンスを作成
        DBRef = FIRDatabase.database().reference()
    }
}

データ追加

指定先と同じ階層のは消える。つまり、sampleの他に同じ階層にデータがあったら更新されて削除される。

let data = ["sample": "add_data"]
DBRef.child("hoge/foo").setValue(data)

スクリーンショット 2017-12-11 22.37.05.png

更新

setValueだと同じ階層のものが消えてしまうので、updateChildValuesを使用

let data = ["update": "updata_data"]
DBRef.child("hoge/foo").updateChildValues(data)

スクリーンショット 2017-12-11 22.47.55.png

削除

DBRef.child("hoge/foo/update").removeValue()

データ取得

let defaultPlace = DBRef.child("hoge/foo/sample")
defaultPlace.observe(.value) { (snap: DataSnapshot) in 
    //処理したい内容
  print((snap.value! as AnyObject).description)}
14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15