LoginSignup
_mitty
@_mitty

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

SwiftUIでFirestoreに保存したデータの取り扱いについて

解決したいこと

SwiftUIの勉強で、Firebaseにデータを保存し、再度するサンプルプログラムをつくっています。
Firebaseで取り出したデータの扱い方について質問です。

FirebaseのHPのドキュメントを確認しながら、なんとかアプリ登録、保存、取得までできましたが、取得したデータはdocument単位?であり、document内にいくつかあるデータを選択的に取り出す方法が分かりません。

わかりづらい説明で恐縮ですが、ソースコード内に、より詳しく状況を説明するためのコメントを追記しています。

よろしくお願いします。

作成したサンプルプログラムの表示画面

Simulator Screen Shot - iPod touch (7th generation) - 2021-05-18 at 14.32.46.png

該当するソースコード

ContentView.swift

//Xcode version 12.4
//Swift version 5.3.2
//Cocoapods version 1.10.1 (pod 'Firebase/Firestore'と書いてpod install)

import SwiftUI
import Firebase

struct ContentView: View {

    @State private var word1 = ""
    @State private var word2 = ""

    @State private var dataDescription = ""

    @State private var word1_fromFirestore = ""
    @State private var word2_fromFirestore = ""

    var body: some View {

        Text("Firestoreテスト")
            .padding()

        VStack {
            HStack {
                Text("入力1")
                TextField("入力したワードはFiresoreに保存", text: $word1)
            }
            HStack {
                Text("入力2")
                TextField("入力したワードはFiresoreに保存", text: $word2)
            }
        }

        Button(action: {
            let db = Firestore.firestore()
            db.collection("collectionnameX").document("docmentnameX").setData([
                "savedata1": word1,
                "savedata2": word2
            ]) { err in
                if let err = err {
                    print("Error writing document: \(err)")
                } else {
                    print("Document successfully written!")
                }
            }
        }){
            Text("Firesoreに保存")
                .border(Color.green, width: 1)
                .cornerRadius(5)
        }
        Button(action: {
            let db = Firestore.firestore()
            let docRef = db.collection("collectionnameX").document("docmentnameX")
            docRef.getDocument { (document, error) in
                if let document = document, document.exists {
                    dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                    print("Document data: \(dataDescription)")
                } else {
                    print("Document does not exist")
                }
            }
        }){
            Text("Firesoreから取得")
                .border(Color.green, width: 1)
                .cornerRadius(5)
        }
        Text("取得したデータを表示")
        //以下 Text("\(dataDescription)")では、
        //"Document data: ["savedata1": あいうえお, "savedata2": かきくけこ]"と表示されます。
        //このうち、savedata1の値「あいうえお」を取り出すにはどのようにすれば良いでしょうか?
        //dataDescription.savedata1のようにやるのだろうと思い試しましたが、うまくいきません。
        Text("\(dataDescription)")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

test_firestore3App.swift

import SwiftUI
import Firebase

@main
struct test_firestore3App: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        return true
    }
}
0

No Answers yet.

Your answer might help someone💌