0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Firestoreを使用したデータの追加、読み取り

Posted at

Firebaseのドキュメントにも書いてある通りだが、ViewControllerにFirebaseをimportしない方法で記述する。

FirestoreContoroller.swift
import UIKit

class FirestoreViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    

    @IBAction func addAction(_ sender: Any) {
        Database.addTest()
      }

      @IBAction func readAction(_ sender: Any) {
        Database.readTest() { users in
          for user in users {
            print("\(user.first), \(user.last), \(user.born)")
          }
        }
      }
    }
UserModel.swift
import Foundation
import FirebaseAuth

struct UserModel: Codable {

  private var _first: String?
  var first: String { _first ?? "" }
  private var _last: String?
  var last: String { _last ?? "" }
  private var _born: Int?
  var born: Int { _born ?? 0 }

  private var _weight: Double?
  var weight: Double { _weight ?? 0 }

  private var _height: String?
  var height: String { _height ?? "" }

  private let auth = Auth.auth()
  var isEmailValidation: Bool {
    auth.currentUser?.isEmailVerified ?? false
  }

  private enum CodingKeys: String, CodingKey {
    case _first = "first"
    case _last = "last"
    case _born = "born"
  }
}
Database.swift
import Foundation
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift


class Database {
  private static let db = Firestore.firestore()

  static func addTest() {

    var ref: DocumentReference? = nil
    ref = db.collection("users").addDocument(data: [
      "first": "Ada",
      "last": "Lovelace",
      "born": 1815
    ]) { err in
      if let err = err {
        print("Error adding document: \(err)")
      } else {
        print("Document added with ID: \(ref!.documentID)")
      }
    }
  }

  static func readTest(completion: (([UserModel]) -> Void)? = nil) {

    let _completion: ((QuerySnapshot?, Error?) -> Void) = { (querySnapshot, err) in

      var users: [UserModel] = []

      if let err = err {
        print("Error getting documents: \(err)")
        completion?(users)
        return
      }

      for document in querySnapshot!.documents {
        if let _user = try? Firestore.Decoder().decode(UserModel.self, from: document.data()) {
          users.append(_user)
        }
      }

      completion?(users)
    }

    db.collection("users").getDocuments(completion: _completion) //全部終わるまで待つ
  }
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?