LoginSignup
9
8

More than 5 years have passed since last update.

Swift 3.0 でのFirebaseDatabaseの読み込み(取得)・書き込み(保存)

Last updated at Posted at 2017-06-23

自分用のメモがわり!

環境 Swift3.0 / Xcode8.3.3

Firebaseデータベースをimportした後の処理。

書き込み

1.まずはReference(参照をつくる)

let ref = Database.database().reference()

注意!: Swift3 とXcode8.3.3では
x FIRDatabase ではなく、○ Dababase らしい。
公式Documentが更新されていないだけ・・・。

2.子要素にランダムで作ったIDのフォルダを生成する。

 let folderRef = ref.child("ExploreFolders").childByAutoId();

childByAutoId()がrandamIDを作ってくれる!便利

3.ランダムIDの下に情報をぶち込む

 let newFolder = ["category": "BARS", "folderName": "JAZZBAR", "imageName":"livehouse1", "spotsNum":8 , "Spots":[]] as [String : Any]
 folderRef.updateChildValues(newFolder)

4 結果(Firebaseのconsole内)

Screen Shot 2017-06-23 at 12.06.25 PM.png

読み込み / 取得

1.書き込みと同じく、参照をつくる

let ref = Database.database().reference()

2.書き込み

self.ref.child("ExploreFolder").observeSingleEvent(of: .value, with: { (snapshot) in


       // "ExploreFolder"の子要素ごとになにかを実行
            for folder in snapshot.children {

                if let snap = folder as? DataSnapshot {
                    print(folder.category) // "category" keyの値がprintされる。
                }
            }

3.結果(Firebaseのconsole内)

Music
BARS

Screen Shot 2017-06-23 at 12.24.03 PM.png

9
8
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
9
8