DEV Community

Cover image for Firestore Swift CRUD

Firestore Swift CRUD

My way to Firestore CRUD for iOS UIKit๐Ÿฅณ,

1. Create a Rule for your data on the Firestore Rule page

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /Adress/{userId} {
      allow read, write: if request.auth != null;
      allow create: if request.auth != null;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Create a Model for your data

I usually use Struct

create a swift file -> and write down you struct

Struct myStruct {

    var name: String
    var city: String
    var state: String
    var UID: String
    var DID: String

    var dict: [String: Any] {
        return[ 
        "name": name,
        "city": city,
        "state": state,
        "UID": UID,
        "DID": DID
       ]
   }
}
Enter fullscreen mode Exit fullscreen mode

3. Create a UserDefaults Object

After user Login save the user ID on UserDefaults as String, then reuse this element in ViewDidLoad() or ViewWillAppear() resuming this value.

4. Create a your first Data

Save to Firestore with:

let db = Firestore.firestore()

then...

 db.collection("Adress").addDocument(data: [

            "name": String(name_label.text ?? ""),
            "city": String(city_label.text ?? ""),
            "state": String(state_label.text ?? ""),
            "UID": String(ID ?? ""),
            "DID": String("")
        ]) { err in
            if let err = err {
                print("Error adding document: \(err)")
            } else {
                //print("Document added with ID: \(ref.documentID)")
                }
            }
Enter fullscreen mode Exit fullscreen mode

5. Read Data

Remember to use the user Identifier you already saved in UserDefault, I usually do this in ViewWillAppear() beacuse of hierarchies...

ID = UserDefaults.standard.object(forKey: "userInfo") as? String

create an array of your struct for your data.

var arrayOfData = [myStruct]()

Then you start read from Firestore:

 let db = Firestore.firestore()

        db.collection("Adress").whereField("UID", isEqualTo: ID!).getDocuments() { [self](querySnapshot, err) in

            if let err = err {
                print("Error getting Firestore data: \(err)")
            }else{
                for document in querySnapshot!.documents {

                let singleData = myStruct(name: document.data()["name"] as? String ?? "", city: document.data()["city"] as? String ?? "", state: document.data()["state"] as? String ?? "",
UID: document.data()["UID"] as? String ?? "",
DID: document.documentID)

self.arrayOfData.append(singleData)
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

5. Update Data

Updating data by documentID and of course user ID ๐Ÿ˜‚

when have you found the right document to update, set the new value for the document.

let DOCREFERENCE = db.collection("Adress").document(documentID!)

            DOCREFERENCE.setData([
                "name": String(name_label.text ?? ""),
            "city": String(city_label.text ?? ""),
            "state": String(state_label.text ?? ""),
            "UID": String(ID ?? ""),
            "DID": String(documentID)
            ])
Enter fullscreen mode Exit fullscreen mode

6. Delete Data

Delete data in a collection (usually UITableView() or UICollectionView())

let db = Firestore.firestore()

db.collection("Adress").document(documentID).delete()

Top comments (0)