Swift

Firebase / Cocoa Pods

khon98 2021. 3. 22. 22:06

Firebase

- 서버 자체를 서비스로 제공

- 데이터 저장, 실시간 데이터 동기화, 사용자 인증, 데이터 분석, A/B Testing 등 많은 기능을 제공

 

Cocoa Pods

- 외부 라이브러리 관리 모듈

- Firebase Ios SDK를 가져오게 도와주는 모듈

 

 

Cocoa Pods 설치 방법

- 구글에 Cocoa Pods 검색 후 사이트에 있는 sudo gem install cocoapods 복사

- 터미널 실행 > 붙여 넣기

- 비밀 번호 입력

 

Firebase SDK 설치 방법

1. Firebase 홈페이지 접속

 

2. 로그인 후 우측 상단 '콘솔로 이동' 클릭

 

3. 프로젝트 추가 클릭 > 프로젝트 이름 설정 > continue > continue > Default account for Firebase 선택 > 프로젝트 생성

 

4. ios 클릭

 

5. 번들 id 추가 후 '계속' 클릭

Bundle Identifier 입력

 

6. GoogleService-Info 파일 다운로드

 

7. 다운로드한 파일 xcode 프로젝트에 추가

 

8. firebase 홈페이지에서 next 클릭

 

9. 터미널 실행 후 생성한 xcode 프로젝트 폴더 주소 입력

( pwd는 현재 터미널에서 접근한 위치가 어딘지 알려주고,

cd 입력 후 원하는 주소 입력하면 해당 위치로 이동,

open . 입력하면 해당 폴더를 open )

- pod이 깔려 있어야 함 (확인 방법: 터미널에 pod --version 입력 후 버전이 나오면 설치가 되어 있는 거고 안 뜨면 설치가 되어 있지 않은 거)

 

10. pod init 입력 > 해당 파일에 podfile이 생성됨 해당 파일 열고 # Pods for Firebase_SDK_Install 밑에 pod 'Firebase/Analytics' 붙여 넣기

 

11. pod install 입력 > 파이어 베이스 홈페이지에서 '계속' 클릭 

 

12. 프로젝트 만든 폴더에 생성된 workspace 파일 열고

import Firebase / FirebaseApp.configure() 입력

 

13. 앱 실행하라고 하면 실행하면 되고 아니면 다음으로 넘어가면 됨

 

 

Realtime Database 만들기

1. 파이어 베이스 홈페이지에서 데이터 베이스를 만들 프로젝트 누르고 좌측 메뉴에 'Realtime Database' 클릭

 

2. 데이터 베이스 만들기 클릭 > 테스트 모드로 설정

 

3. workspace 생성된 파일에 podfile 실행 후 pod 'Firebase/Analytics' 밑에 pod 'Firebase/Database' 입력

 

4. 터미널에 pod install 입력

 

5. 코드 입력 / 오류 발생하면 클린 빌드하고 재실행

import Firebase / let db 코드 추가

 

6. 파이어 베이스 홈페이지 > 데이터 > add child 클릭 > 이름, 값 추가

 

 

 

 

더보기
import UIKit
import Firebase

class ViewController: UIViewController {
    
    @IBOutlet weak var dataLabel: UILabel!
    @IBOutlet weak var numOfCustomers: UILabel!
    
    let db = Database.database().reference()
    
    var customers: [Customer] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        updateLabel()
        
        saveBasicTypes()
//        saveCustomers()
        
        fetchCustomers()
        
//        updateBasicType()
//        deleteBasicType()
    }
    
    func updateLabel() {
        // 파이어 베이스에 있는 데이터 firstdata에 있는 value 값을 가져옴
        db.child("firstdata").observeSingleEvent(of: .value) { snapshot in
            print("\(snapshot)")
            
            let value = snapshot.value as? String ?? ""
            
            DispatchQueue.main.async {
                self.dataLabel.text = value // dataLabel에 snapshot 값을 넣어 줌
            }
        }
    }
    
    @IBAction func createCustomer(_ sender: Any) {
        saveCustomers()
    }
    
    @IBAction func fetchCustomer(_ sender: Any) {
        fetchCustomers()
    }
    
    func updateCustomers() {
        guard customers.isEmpty == false else { return }
        customers[0].name = "khon50"
        
        let dictionary = customers.map { $0.toDictionary }
        db.updateChildValues(["customers": dictionary])
    }
    
    @IBAction func updateCustomer(_ sender: Any) {
        updateCustomers()
    }
    
    func deleteCustomers() {
        db.child("customers").removeValue()
    }
    
    @IBAction func deleteCustomer(_ sender: Any) {
        deleteCustomers()
    }
    
}



// MARK: Database에 데이터 가져와서 파싱하기
extension ViewController {
    func fetchCustomers() {
        db.child("customers").observeSingleEvent(of: .value) { snapshot in
            print("\(snapshot.value)")
            
            do {
                let data = try JSONSerialization.data(withJSONObject: snapshot.value, options: [])
                let decoder = JSONDecoder()
                let customers: [Customer] = try decoder.decode([Customer].self, from: data)
                self.customers = customers
                
                DispatchQueue.main.async {
                    self.numOfCustomers.text = "Num of Customers: \(customers.count)"
                }
            } catch let error {
                print("error: \(error.localizedDescription)")
            }
        }
    }
}

// MARK: Database에 데이터 추가
extension ViewController {
    func saveBasicTypes() {
        db.child("Int").setValue(3)
        db.child("Double").setValue(4.8)
        db.child("Str").setValue("String Value - 안녕")
        db.child("array").setValue(["a", "b", "c"])
        db.child("Dict").setValue(["ID": "khon", "age": 50, "city": "seoul"])
    }
    
    func saveCustomers() {
        let books = [Book(title: "abcd", author: "abcd"), Book(title: "efgh", author: "efgh")]
        
        let customer1 = Customer(id: "\(Customer.id)", name: "khon", books: books)
        Customer.id += 1
        let customer2 = Customer(id: "\(Customer.id)", name: "khon01", books: books)
        Customer.id += 1
        let customer3 = Customer(id: "\(Customer.id)", name: "khon02", books: books)
        Customer.id += 1
        
        db.child("customers").child(customer1.id).setValue(customer1.toDictionary)
        db.child("customers").child(customer2.id).setValue(customer2.toDictionary)
        db.child("customers").child(customer3.id).setValue(customer3.toDictionary)
    }
}

// MARK: Database 데이터 수정 및 삭제
extension ViewController {
    func updateBasicType() {
        db.updateChildValues(["Int": 6])
        db.updateChildValues(["Double": 7.9])
        db.updateChildValues(["Str": "Change String"])
    }
    
    func deleteBasicType() {
        db.child("Int").setValue(3)
        db.child("Double").setValue(4.8)
        db.child("Str").setValue("String Value - 안녕")
    }
}

struct Customer: Codable {
    let id: String
    var name: String
    let books: [Book]
    
    var toDictionary: [String: Any] {
        let booksArray = books.map { $0.toDictionary }
        let dict: [String: Any] = ["id": id, "name": name, "books": booksArray]
        return dict
    }
    static var id: Int = 0
}

struct Book: Codable {
    let title: String
    let author: String
    
    var toDictionary: [String: Any] {
        let dict: [String: Any] = ["title": title, "author": author]
        return dict
    }
}