Understanding How SwiftUI Saves Custom Objects to Firebase

Asked 1 years ago, Updated 1 years ago, 43 views

Question details
I'm studying how to save and retrieve data from SwiftUI to Firestore.
I tried to save the custom object and write a test code to retrieve it, but I couldn't deal with the following error:
I have used the one listed in the official Firebase document, but how should I fix it?
The error content has been added to the code as a comment.

Test Code

import SwiftUI
import Firebase

struct ContentView:View {
    
    let savedata=SaveData(savename: "SaveName", savedate:Date(), savedataarray:["SaveDataA", "SaveDataB", "SaveDataC", saveint:123)
    @State private var savedata_fromFirebase=SaveData(savename:", savedate:Date(), savedataarray:["Initial View A", "Initial View B", "Initial View C", saveint:0)
    
    varbody:someView {

        VStack {
            //-------------------------------------------------------------------------
            Button(action: {
                let db = Firestore.firestore()
                do{
                    // Cannot convert value of type 'SaveData' to expected argument type '[String:Any]'
                    // Extraordinary argument label 'from:'in call
                    try db.collection("collectionnameY").document("docentnameY").setData(from:savedata)

                } catchlet error {
                    print("Error writing savedata to Firestore:\(error)")
                }
            }){
                Text ("Save Custom Objects to Firestore")
                    .border (Color.green, width:1)
            }
            //-------------------------------------------------------------------------
            Button(action: {
                let db = Firestore.firestore()
                let docRef=db.collection("collectionnameY").document("docmentnameY")
                docRef.getDocument {( document, error) in
                    let result = Result {
                      try document?.data(as:SaveData.self) // Argument passed to call that takes no arguments
                    }
                    switch result {
                    case.success(let savedata):
                        iflet savedata=savedata{
                            print("SaveData:\(savedata)")
                        } else{
                            print("Document does not exist")
                        }
                    case.failure(let error):
                    print("Error decoding savedata:\(error)")
                    }
                }
            }){
                Text ("Get Custom Objects from Firestore")
                .border (Color.green, width:1)
            }
            //-------------------------------------------------------------------------
            Text("The display will be updated after the custom object is retrieved (below)")
            Text("\(savedata_fromFirebase.savename!")"
            Text("\"(savedata_fromFirebase.savedate!")
            // Instance method 'appendInterpolation(_:formatter:) 'requires that' [String] ? 'inherit from 'NSObject'
            Text("\(savedata_fromFirebase.savedataarray)")
            Text("\(savedata_fromFirebase.saveint!")
        }

    }
}

structureSaveData:Codable{
    let savename —String?
    let savedate —Date?
    let savedataarray: String?
    let saveint: Int?
    
    enum codingKey: String, codingKey {
        case savename
        case savedate
        case savedataarray
        case saveint
    }
}

structureContentView_Previews:PreviewProvider{
    static var previews:someView {
        ContentView()
    }
}

swift firebase swiftui

2022-09-30 20:17

1 Answers

Based on your advice, SwiftUI can now save custom objects to Firebase, so I will summarize the steps briefly.

1.
Check SwiftUI in Xcode to create a new project
By default, the two filenames App.swift and ContentView.swift should have been created.

2.
In X-code, click
→File
→ Swift Packages
→ Add Package Dependency...
→ Enter https://github.com/firebase/firebase-ios-sdk.git in the URL
→ Install (time consuming) firebase, firebasefirestore, and firebasefirestore-swift

3.
Go to Firebase's official website and register the app (I will proceed with my account on Firebase on the assumption that I have already created it)
*If you follow the guide on the official website and proceed with the registration, you will be told to install it using CocoaPods, but you can ignore it and move on

4.
Rewrite the filename App.swift as follows:

import SwiftUI
import Firebase // Add
import FirebaseFirestoreSwift // Add
import FirebaseFirestore // Add

@main
structure test_Firebase5App:App{
    // Add (from here)
    init(){
        FirebaseApp.configure()
    }
    // Additional note (up to here)
    varbody:someScene{
        WindowGroup {
            ContentView()
        }
    }
}

Similarly, if you want to use firebase, click

import Firebase // Add
import FirebaseFirestoreSwift // Add
import FirebaseFirestore

Add

That's all.
Please let me know if you have any questions.(The respondents themselves may not be able to give a useful answer because they are struggling and do not understand many things.)
With SwiftPackageManager, I personally found it convenient, with fewer steps than Cocoapods.


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.