Firebase 서버 연동하기

파이어베이스

✔️ 핵심: Realtime Database = Data Sync

✔️ Storage

✔️ Authentication

✔️ FCM: Firebase Cloud Message

✔️ Crash report

Podfile

pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Storage'

ref.observe 기본 메소드

var ref: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
   
   // FB의 최상위 노드
    ref = Database.database().reference()
   
   // 원하는 곳을 observing 하는 개념으로 realtime db 실현
    ref.observe(DataEventType.childAdded) { (DataSnapshot) in
        print("Item Addeds")
    }
   
    ref.observe(DataEventType.childRemoved) { (DataSnapshot) in
        print("Item Removed Key: ")
        print("Item Removed Value: ")
    }
   
    ref.observe(.childChanged) { (snapshot) in
        dump(snapshot.value)
    }
}
    

응용

var currentUser: UserModel!    
var uid: String {
    return currentUser.uid
}
    
private init() {
    Auth.auth().addStateDidChangeListener { [weak self] (auth, user) in
        if let user = user {
            self?.currentUser = UserModel(uid: user.uid)
        }
    }
}
    
func uploadImg(selectedImgData : Data) {
    let filename = NSUUID().uuidString
    Storage.storage().reference().child("profile_imgs").child(filename).putData(selectedImgData, metadata: nil) { (metadata, error) in
        guard let profileImgUrl = metadata?.downloadURL()?.absoluteString else {return}
        let dic = ["profile_img_url" : profileImgUrl]
        Database.database().reference().child(self.uid).updateChildValues(dic, withCompletionBlock: { (error, ref) in
            if error == nil {
                print("uploadImg 성공")
            }else {
                print(error!.localizedDescription)
            }
        })
    }
}