Swift中Firestore文档对象类型字段的处理及数据添加问题
Hey there! Let’s work through your problem with adding data to a Firestore document that has a nested language object. From what you shared, you’re using SwiftJSON for parsing but struggling to get new data into that nested structure. Let’s break down the common pitfalls and solutions.
First, note that the code you provided is for retrieving a document (getDocument), not adding/updating data—so let’s focus on the write operations that might be causing the issue.
Common Issues & Fixes
1. Incorrectly Structuring Nested Data for Write
Firestore expects nested objects to be passed as Swift dictionaries (or Codable models) that match the exact structure of your document. If the structure doesn’t align, the write will fail silently or throw an error.
Example: Using updateData for Nested Fields
This method is great if you want to update just the language field without overwriting other parts of the document:
// Build your nested language object let languagePayload: [String: Any] = [ "record": 150, // Match the Int type in Firestore "daily": [ "date": "2024-05-20", "streak": 7 ] // Nested daily object ] let docRef = db.collection("users").document(uid).collection("activities").document(uid) // Update the document with the nested data docRef.updateData([ "language": languagePayload ]) { error in if let error = error { print("Failed to update: \(error.localizedDescription)") } else { print("Nested data updated successfully!") } }
Example: Using Codable Models (Cleaner for Complex Structures)
If you’re using models to map your Firestore data, make sure they conform to Codable so you can directly encode them:
// Define your models to match Firestore's structure struct Daily: Codable { var date: String var streak: Int } struct Language: Codable { var record: Int var daily: Daily } // Create an instance of your model let dailyData = Daily(date: "2024-05-20", streak: 7) let languageData = Language(record: 150, daily: dailyData) // Write to Firestore using setData(from:) do { // Use merge: true to avoid overwriting existing unrelated fields try docRef.setData(from: languageData, merge: true) print("Data added via model successfully!") } catch { print("Error encoding model: \(error.localizedDescription)") }
2. Firestore Security Rules Blocking Writes
Even if your code is correct, your Firestore security rules might be preventing writes. Double-check your rules in the Firebase Console:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Ensure authenticated users can write their own activities match /users/{userId}/activities/{activityId} { allow read, write: if request.auth != null && request.auth.uid == userId; // For testing only: temporarily open access (don't use in production!) // allow read, write: if true; } } }
3. Data Type Mismatches
Make sure the data types you’re passing exactly match what’s defined in Firestore:
recordmust be anInt(not aStringorDouble)dailymust be an object (dictionary or model) — not an array or primitive type
Key Troubleshooting Steps
- Always print the error from your write completion handler—it will tell you exactly what’s wrong (e.g., permission denied, invalid data type)
- Verify your document path is correct (you’re using
uidfor both the user document and the activity document—double-check if that’s intentional) - Use the Firebase Console to manually inspect the document structure and confirm your write payload matches it
内容的提问来源于stack exchange,提问作者AnaMM

