개발하는 동글 :]

[TIL],[UIKit],[FireBase 사용해보기!] 본문

카테고리 없음

[TIL],[UIKit],[FireBase 사용해보기!]

동글하다 2023. 10. 17. 00:06

1. FireBase 연결하기

1.1 Firebase 프로젝트 생성하기

1.2  iOS 버튼을 눌러서 App 등록하기

1.3 app등록하기

1.4 SPM에서 FireBase 패키지 추가

1.5 GoogleService - Info 파일 추가

1.6 초기화 코드 추가

import UIKit
import FirebaseCore

@main
class AppDelegate: UIResponder, UIApplicationDelegate {



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }


}

2. Firebase Data Manager로 CRUD 구현해 보기!

//
//  FireabaseDataManager.swift
//  testProject
//
//  Created by SeoJunYoung on 10/16/23.
//

import Foundation
import FirebaseCore
import FirebaseFirestore
import FirebaseFirestoreSwift

struct TestData: Codable {
    var first: String
    var second: String
    var three: String
}

struct FBDataManager {
    
    let db = Firestore.firestore()
    
    func create(completion: @escaping () -> Void) {
        db.collection("users").addDocument(
            data:[
                "first" : "1",
                "second" : "2",
                "three" : "3"
            ]) { error in
            completion()
        }
    }
    
    func read(completion: @escaping ([TestData]) -> Void) {
        
        db.collection("users").getDocuments {data, error in

            guard let datas = data?.documents else { return }
            
            var temp:[TestData] = []
            
            for data in datas {
                do {
                    let res = try Firestore.Decoder().decode(TestData.self, from: data.data())
                    temp.append(res)
                } catch {
                    print(error)
                }
            }
            completion(temp)
        }
    }
    
}