【Swift】udemyでFirebaseを習ったので復習

Swiftで重要なFirebaseudemyで学んだので、備忘録として書き記す。

 

 

Firebaseを使用する準備

 

AppDelegateにFirebaseのimport文と使用許可?のコードを書く。

f:id:nekokichi_yos2:20181003220444p:plain

 

ターミナルでpod関連をインストール

  

ターミナルで、

 

pod init

 

を打ち、生成されたPodfile

 

pod

 

と書き、ターミナルで

 

pod install

 

と打つ。

 

 

使いたいViewControlle

import Firebase

する。

 

データベースからデータを取得する流れ

 

  1. 保存したいデータを作成
  2. 指定したデータベースの階層下に保存
  3. データベースのURLを参照してデータを取り出す
  4. 取り出したデータを別に作ったPostクラスの変数に入れる
  5. セルなどに表示する
  6. 2に戻る

 

データベースの参照URLを生成

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

データを保存するのに必要な変数を別クラスで宣言

 

f:id:nekokichi_yos2:20181003222156p:plain

 

データベースのpost階層下のデータを取得する 

 

//保存するデータをuserNameとcommentとする
//保存したデータは各postDataに格納される
//それらのPostクラスをpost_Arrayでまとめて管理する
//Post - データ群を持つデータ - userName, comment
var post_Array = [Post]()
var postData = Post()

//データを取得する
ref.child(“post”).observeSingleEvent(of: .value) { (snap, error) in

	//snapにはキーで名付けられたデータが辞書型で渡される
	//例:[“userName” : “Mike”]など
	let snapData = snap.value as? [String: NSDictionary]

	//もしデータがなければ
	if snapData == nil {
		return 
	}

	//
	for (_, post) in snapData! {

		if let userName = post[“userName”] as? String, let comment = post[“comment”] as? String {
			
			//Post.swiftの変数にデータを入れる
			self.postData.userName = userName
			self.postData.comment = comment

		}
		
		//データをまとめてpost_Arrayに入れる
		self.post_Array.append(self.postData)

	}

}

 

取得したデータをセルに表示させる

func tableView(…, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
	
	//セルを生成
	let cell = tableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath)

	//Tag:1のUILabelをOutlet紐付けなしで紐付け
	let userNameLabel = cell.viewWithTag(1) as! UILabel
	//indexPath.rowに該当するPost()クラスのuserNameを入れる
	userNameLabel.text = posts[indexPath.row].userName
	
	let commentLabel = cell.viewWithTag(2) as! UILabel
	//indexPath.rowに該当するPost()クラスのuserNameを入れる
	commentLabel.text = posts[indexPath.row].comment

	return cell

}

ユーザー名とコメントをデータベースに保存する

//post階層下にデータ群をまとめる配列?データを生成
//childByAutoId:階層下のデータを扱う階層名を自動生成?
let rootRef = Database.database().reference(fromURL: “Firebaseで作ったデータベースのURL”).child(“post”).childByAutoId()

//保存したいデータの型を宣言
let feed = [“userName”:Label.text , “comment”:textField.text] as [String: Any]

//指定した階層にデータを保存
rootRef.setValue(feed)

 

まとめ

  

Userdefaults以上のデータ連携を可能にするFirebaseは、開発に重要な技術でありながら、初心者にはめちゃむずい。

 

udemyで初めてFirebaseに触れた時は、なんのこっちゃだった。

 

自分で写形したり、ほかの講座でまた触れたりしていくと、何となく理解できるようになった。

 

やはり、その技術にどれだけ触れられるかで理解度が変わってくる。