【Swift】Firestore에 데이터를 추가·취득
데이터 쓰기
컬렉션의 필드에는 Messages, 문서는 고유 ID,
문서 필드에 메시지 데이터를 포함한다고 가정합니다.
import FirebaseFirestore
...
Firestore.firestore().collection("Messages").document().setData([
"date": Date(),
"senderId": "testId",
"text": "testText",
"userName": "testName"
])
collection("Messages")에서 다음 이미지와 같이 컬렉션 이름이 생성됩니다.
document()와 같이 () 안을 지정하지 않으면 고유 ID가 흔들립니다.
마지막으로 setData로 메시지 데이터를 map(사전)으로 쓰고 있습니다.
반영된 데이터

데이터 얻기
Firestore에서 얻은 데이터는 다루기 쉽도록
구조체를 형태로 해 앱측에서 처리를 한다고 합니다.
struct FirestoreData {
var date: Date?
var senderId: String?
var text: String?
var userName: String?
}
import FirebaseFirestore
...
...
Firestore.firestore().collection("Messages").getDocuments(completion: {
(document, error) in
if error != nil {
print("ChatViewController:Line(\(#line)):error:\(error!)")
} else {
if let document = document {
for i in 0..<document.count {
var storeData = FirestoreData()
storeData.date = (document.documents[i].get("date")! as! Timestamp).dateValue()
storeData.senderId = document.documents[i].get("senderId")! as? String
storeData.text = document.documents[i].get("text")! as? String
storeData.userName = document.documents[i].get("userName")! as? String
self.firestoreData.append(storeData)
print(self.firestoreData)
}
}
}
})
Firestore.firestore().collection("Messages").getDocuments에서
Messages 컬렉션 부하의 문서와 그 데이터를 모두 취득합니다.
문서는 여러 번 반환되기 때문에 for in 문으로 처리합니다.
document.documents[인덱스 번호]로 문서의 데이터에 액세스하고,
문서 부하의 데이터에는 document.documents[인덱스 번호].get()로 액세스합니다.
get()내에 키명을 지정하는 것으로, 문서 부하의 데이터를 취득할 수가 있습니다.
형식은 여기에서 명시해야 합니다.
주의사항
Firestore의 날짜 정보는 Date() 형식으로 전달해도 Timestamp 형식으로 반환되므로
Timestamp로 캐스팅하고 .dateValue()로 Date 형식으로 변환해야합니다.
Reference
이 문제에 관하여(【Swift】Firestore에 데이터를 추가·취득), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/Sossiii/items/a14490e1c71e2949e6c0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)