How to map the nested data in a document from Firestore by Swift? - swift

I have a document data structure on Firestore like this:
pic1
pic2
So there are 2 map-objects inside the document and a collection and a another document inside this document
Then I create 3 model swift files for this document
task:
struct task {
var Name: String
var Address: String
var Car: CarModel
car Price: PriceModel
var dictionary: [String:Any] {
return [
"Name" : Name,
"Address" : Address,
"Car" : CarModel,
"Price" : PriceModel
]
}
init?(data: [String:Any]) {
guard let Name = dictionary["Name"] as? String,
let Address = dictionary["Address"] as? String,
let Car = ditionary["car"] as? CarModel,
let Price = dictionary["price"] as? PriceModel else{
return nil
}
self.Name = Name
self.Address = Address
self.Car = Car
self.Price = Price
}
}
CarModel:
struct CarModel {
var brand: String
var model: String
var year: String
var dictionary: [String:Any] {
return [
"brand" : brand,
"model" : model,
"year" : year,
]
}
init?(data: [String:Any]) {
guard let brand = dictionary["brand"] as? String,
let model = dictionary["model"] as? String,
let year = ditionary["year"] as? String else{
return nil
}
self.brand = brand
self.model = model
self.year = year
}
}
PriceModel:
struct PriceModel {
var basic: Int
var extra: Int
var dictionary: [String:Any] {
return [
"basic" : basic,
"extra" : extra,
]
}
init?(data: [String:Any]) {
guard let basic = dictionary["basic"] as? Int,
let extra = ditionary["extra"] as? Int else{
return nil
}
self.basic = basic
self.extra = extra
}
}
Then download the data with this following code:
func loadDataFromFirestore(completion: #escaping (Bool) -> ()) {
var success: Bool = false
DispatchQueue.global(qos: .userInteractive).async {
let downloadGroup = DispatchGroup()
let colRef = db.collection("tasks")
downloadGroup.enter()
colRef.getDocuments() { (querySnapshot, error) in
if let error = error {
print("Error: \(error)")
return
}
for document in querySnapshot!.documents{
let result = document.data()
print (result)
if let data = task(data: result){
print(data)
}
}
success = true
downloadGroup.leave()
}
downloadGroup.wait()
DispatchQueue.main.async {
completion(success)
}
}
}
I can get the data with comment the CarModel and PriceModel, but if I uncomment these two, it will let my app crash!
So how could I get the map-object to adapt to my code?
And the second question is: How can I get the document inside a document's collection with this kind of code?

Related

Firebase - How do I read this map via embedded structs?

I am reading data from Firestore to be able to populate into expanding tableview cells. I have a really simple struct:
protocol PlanSerializable {
init?(dictionary:[String:Any])
}
struct Plan{
var menuItemName: String
var menuItemQuantity: Int
var menuItemPrice: Double
var dictionary: [String: Any] {
return [
"menuItemName": menuItemName,
"menuItemQuantity": menuItemQuantity,
"menuItemPrice": menuItemPrice
]
}
}
extension Plan : PlanSerializable {
init?(dictionary: [String : Any]) {
guard let menuItemName = dictionary["menuItemName"] as? String,
let menuItemQuantity = dictionary["menuItemQuantity"] as? Int,
let menuItemPrice = dictionary["menuItemPrice"] as? Double
else { return nil }
self.init(menuItemName: menuItemName, menuItemQuantity: menuItemQuantity, menuItemPrice: menuItemPrice)
}
}
And this is embedded in this struct:
protocol ComplainSerializable {
init?(dictionary:[String:Any])
}
struct Complain{
var status: Bool
var header: String
var message: String
var timeStamp: Timestamp
var email: String
var planDetails: Plan
var dictionary: [String: Any] {
return [
"status": status,
"E-mail": header,
"Message": message,
"Time_Stamp": timeStamp,
"User_Email": email,
"planDetails": planDetails
]
}
}
extension Complain : ComplainSerializable {
init?(dictionary: [String : Any]) {
guard let status = dictionary["status"] as? Bool,
let header = dictionary["E-mail"] as? String,
let message = dictionary["Message"] as? String,
let timeStamp = dictionary["Time_Stamp"] as? Timestamp,
let email = dictionary["User_Email"] as? String,
let planDetails = dictionary["planDetails"] as? Plan
else { return nil }
self.init(status: status, header: header, message: message, timeStamp: timeStamp, email: email, planDetails: planDetails)
}
}
However, I am not able to query any data from Firestore which looks like this:
Here is my query, although I am just reading all the files:
let db = Firestore.firestore()
var messageArray = [Complain]()
func loadMenu() {
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let error = error {
print("error:\(error.localizedDescription)")
} else {
self.messageArray = documentSnapshot!.documents.compactMap({Complain(dictionary: $0.data())})
for plan in self.messageArray {
print("\(plan.email)")
}
DispatchQueue.main.async {
self.testTable.reloadData()
}
}
}
}
What am I doing wrong?
EDIT:
As suggested, here is the updated embedded struct:
import Foundation
// MARK: - Complain
struct Complain: Codable {
let eMail, message, timeStamp, userEmail: String
let status: Bool
let planDetails: PlanDetails
enum CodingKeys: String, CodingKey {
case eMail = "E-mail"
case message = "Message"
case timeStamp = "Time_Stamp"
case userEmail = "User_Email"
case status, planDetails
}
}
// MARK: - PlanDetails
struct PlanDetails: Codable {
let menuItemName: String
let menuItemQuantity: Int
let menuItemPrice: Double
}
Using quicktype.io, you can generate the struct. From there, all you need to do is run this tiny fragment of code within your response handler.
var compainArray = [Complain]()
func loadMenu() {
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let error = error {
print("error:\(error.localizedDescription)")
} else {
guard let snapshot = documentSnapshot else {return}
for document in snapshot.documents {
if let jsonData = try? JSONSerialization.data(withJSONObject: document.data()){
if let converted = try? JSONDecoder().decode(Complain.self, from: jsonData){
self.compainArray.append(converted)
}
}
}
DispatchQueue.main.async {
self.testTable.reloadData()
}
}
}
}
Which will handle the looping, and mapping of certain variables. Let me know if you have any trouble with this.

How do I add firestore document Id to my model and subsequently to the array?

I have a struct "Order" that contains a field called orderId:
protocol OrderSerializable {
init?(dictionary:[String:Any])
}
struct Order {
var orderId: String
var status: Int
var currentTotal: Double
var Dictionary:[String : Any] {
return [
"orderId": orderId,
"status": status,
"currentTotal": currentTotal
]
}
}
extension Order : OrderSerializable {
init?(dictionary: [String : Any]) {
guard let orderId = dictionary["orderId"] as? String,
let status = dictionary["status"] as? Int,
let currentTotal = dictionary["currentTotal"] as? Double
else { return nil }
self.init(orderId: orderId, status: status, currentTotal: currentTotal)
}
}
I need to add the firestore document Id to the orderId field in the model array i.e. "ordersArray". How would I go about doing that?
This is my query code so far and I have indicated the line that I need:
orderRef.getDocuments() {
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
guard let documents = querySnapshot?.documents else { return }
for document in documents {
let orderDictionary = document.data() as [String : Any]
let order = Order(dictionary: orderDictionary)
// Here I want to append the firestore documentId to order.orderId before appending it to the array
self.ordersArray.append(order!)
}
DispatchQueue.main.async {
self.ordersTableView?.reloadData()
}
}
}
Thanks in advance.
Different error
Modify your extension to accept the documentId as an additional parameter, and pass this to the created Order object.
protocol OrderSerializable {
init?(dictionary:[String:Any], id: String)
}
extension Order : OrderSerializable {
init?(dictionary: [String : Any], id: String) {
guard let status = dictionary["status"] as? Int,
let currentTotal = dictionary["currentTotal"] as? Double
else { return nil }
self.init(orderId: id, status: status, currentTotal: currentTotal)
}
}
Then, when you create each order, pass the documentId as the id parameter.
orderRef.getDocuments() {
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
guard let documents = querySnapshot?.documents else { return }
for document in documents {
let orderDictionary = document.data() as [String : Any]
let order = Order(dictionary: orderDictionary, id: document.documentId)
self.ordersArray.append(order!)
}
DispatchQueue.main.async {
self.ordersTableView?.reloadData()
}
}
}
Alternatively, you could have stored the orderId directly in the document itself, so that it would be passed in along with the dictionary, avoiding the need for using documentId.

How to get an array field from Firestore and write in struct field in Swift?

The problem that I faced is, I can reach every field in Firestore and write in structs except array&map field.
My firestore data is something like:
let data : [String : Any] = [
"name" : "House A",
"price" : 2000,
"contents" : [
"water" : true,
"internet" : false
]
]
Here is getDocument function:
let docRef = db.collection("example").document("example")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let data = Houses(Doc: document)
...
...
...
} else {
print(error, "Item not found")
}
}
Here is my structs :
struct Houses {
var name: String?
var price: Int
var contents : Contents
init(Doc: DocumentSnapshot){
self.name = Doc.get("name") as? String ?? ""
self.price = Doc.get("price") as! Int
self.contents = Doc.get("contents") as! Contents
}
}
struct Contents {
var water: Bool
var internet : Bool
init?(data: [String: Any]) {
guard let water = data["water"] as? Bool,
let internet = data["internet"] as? Bool else {
return nil
}
self.water = water
self.internet = internet
}
}
The other version of Contents :
struct Contents {
var water: Bool
var internet : Bool
init(Doc: DocumentSnapshot){
self.water = Doc.get("water") as! Bool
self.internet = Doc.get("internet") as! Bool
}
}
UPDATED
The problem solved with changing this line:
self.contents = Doc.get("contents") as! Contents
to;
self.contents = Contents(data: Doc.get("contents") as! [String : Any])
name and price returns what I expected but contents always return nil. I tried to configure Contents but results are same. I think, I have to configure struct named Contents.
Any help would be appreciated.

Firebase: How to put data in a child that's already created with childbyAutoID

people in my app sometimes needs to update the status of something. Now can you choose of 2 things: The so called "Rollerbank" is still there or the "Rollerbank" is removed. The users can create a data ref. The id that will be created by childbyAutoID. Now is my question how to get the right child and update some childs with a value. My post:
class Post {
let ref: DatabaseReference!
var TypeControle: String = ""
var Stad: String = ""
var Tijd: String = ""
var TijdControle: String = ""
var TijdControleniet: String = ""
var Latitude: String = ""
var Longitude: String = ""
var Extrainformatie: String = ""
var Staater: String = ""
var Staaternietmeer: String = ""
init(TypeControle: String) {
self.TypeControle = TypeControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Stad: String){
self.Stad = Stad
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Tijd: String) {
self.Tijd = Tijd
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Latitude: String) {
self.Latitude = Latitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Longitude: String) {
self.Longitude = Longitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Extrainformatie: String) {
self.Extrainformatie = Extrainformatie
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Staater: String) {
self.Staater = Staater
ref = Database.database().reference().child("Rollerbanken").child("Controletest").childByAutoId()
}
init(Staaternietmeer: String) {
self.Staaternietmeer = Staaternietmeer
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControle: String) {
self.TijdControle = TijdControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControleniet: String) {
self.TijdControleniet = TijdControleniet
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init() {
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
TypeControle = value["TypeControle"] as! String
Stad = value["Stad"] as! String
Tijd = value["Tijd"] as! String
Latitude = value["Latitude"] as! String
Longitude = value["Longitude"] as! String
Extrainformatie = value["Extrainformatie"] as! String
Staater = value["Staater"] as! String
Staaternietmeer = value["Staaternietmeer"] as! String
TijdControle = value["TijdControle"] as! String
TijdControleniet = value["TijdControleniet"] as! String
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"TypeControle" : TypeControle,
"Stad" : Stad,
"Tijd" : Tijd,
"Latitude" : Latitude,
"Longitude" : Longitude,
"Extrainformatie" : Extrainformatie,
"Staater" : Staater,
"Staaternietmeer" : Staaternietmeer,
"TijdControle" : TijdControle,
"TijdControleniet" : TijdControleniet
]
}
}
Data for the TableViewCell:
class ControleTableViewCell: UITableViewCell {
#IBOutlet weak var storyControle: UILabel!
#IBOutlet weak var storyTijd: UILabel!
var post: Post! {
didSet {
storyControle.text = "\(post.Staaternietmeer)"
storyTijd.text = "\(post.TijdControleniet)"
storyControle.text = "\(post.Staater)"
storyTijd.text = "\(post.TijdControle)"
}
}
How my update button looks like:
#IBAction func Update(_ sender: Any) {
let alertController1 = UIAlertController(title: "Update melden" , message: "De rollerbank", preferredStyle: .alert)
// Create the actions
let RollerbankAction1 = UIAlertAction(title: "Staat er nog steeds", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("Ja Pressed")
self.newStory.Staater = self.Staater
self.newStory.TijdControle = self.TijdControle
self.newStory.save()
}
let cancelAction1 = UIAlertAction(title: "Staat er niet meer", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"
self.newStory.Staaternietmeer = self.Staaternietmeer
self.newStory.TijdControleniet = Tijd
self.newStory.save()
}
alertController1.addAction(RollerbankAction1)
alertController1.addAction(cancelAction1)
self.present(alertController1, animated: true, completion: nil)
}
This is the Structure that i use. If i run all this code, the new data will go in a other childbyAutoID and thats not what i want. It just needs to update/setvalue in the cleare space named "Staaternietmeer" and "TijdControleniet". Can anybody help me with that?
You would then need to store the Push ID somewhere so that you can reuse it later.
To generate a unique Push ID you would use :
Database.database().reference().childByAutoId()
And to store it somewhere :
let postKey = Database.database().reference().childByAutoId().key
And then, say you need a method to share a post for example, and want to add this post to multiple nodes, that's how it may look like :
func sharePost(_ postContent: String, completion: #escaping (Bool) -> ()) {
guard let currentUserId = Auth.auth().currentUser?.uid else {
completion(false)
return
}
let postKey = Database.database().reference().childByAutoId().key
let postData: [String: Any] = [ "content": "blabla",
"author": currentUserId ]
let childUpdates: [String: Any] = ["users/\(currentUserId)/posts/\(postKey)": true,
"posts/\(postKey)": postData ]
Database.database().reference().updateChildValues(childUpdates, withCompletionBlock: { (error, ref) in
guard error == nil else {
completion(false)
return
}
completion(true)
})
}
Now to access the unique Push ID later on, you would use :
Database.database().reference().observe(.childAdded, with: { (snapshot) in
// Here you get the Push ID back :
let postKey = snapshot.key
// And others things that you need :
guard let author = snapshot.childSnapshot(forPath: "author").value as? String else { return }
guard let content = snapshot.childSnapshot(forPath: "content").value as? String else { return }
// Here you store your object (Post for example) in an array, and as you can see you initialize your object using the data you got from the snapshot, including the Push ID (`postKey`) :
posts.append(Post(id: postKey, content: content, author: author))
})

groupBy array by two values in swift

I'm using this extension of Array to groupBy:
func groupBy <U> (groupingFunction group: (Element) -> U) -> [U: Array] {
var result = [U: Array]()
for item in self {
let groupKey = group(item)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += [item]
} else {
result[groupKey] = [item]
}
}
return result
}
And trying to make a dictionary from teamId and rank (custom properties of my object from array).
self.items = myArray.groupBy {
team in
if team.rank == nil {
return team.teamId!
} else {
return team.rank!
}
}
My case looks something like this:
[{
"team_id": "4",
"team_name": "T16",
"rank": "3"
},
,{
"team_id": "4",
"team_name": "T16",
"rank": "2"
},
{
"team_id": "4",
"team_name": "T16",
"rank": "1"
}
,{
"team_id": "5",
"team_name": "T16",
"rank": null
}]
desired output:
let teams : [String: TeamItem] = [ "4" : TeamItem.rank3, "4-2" : TeamItem.rank2, "4-1" : TeamItem.rank1, "5" : TeamItem]
EDIT 2
func requestTeamData(listener:([TeamItem]) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let baseURL: String = self._appSettings.getPathByName(EndPoint.BASE_URL.rawValue) as! String
let paths: NSDictionary = self._appSettings.getPathByName(EndPoint.PATH.NAME.rawValue) as! NSDictionary
let teamPaths: NSDictionary = paths.objectForKey(EndPoint.PATH.TEAM.KEY.rawValue) as! NSDictionary
let path = teamPaths.valueForKey(EndPoint.PATH.TEAM.PATH.rawValue) as! String
request(.GET, baseURL + path, parameters:[:])
.responseCollection { (_, _, team: [TeamItem]?, error) in
if let team = team {
dispatch_async(dispatch_get_main_queue()) {
listener(team)
}
}
}
}
}
Calling the API, straightforward
DataProvider.getInstance().requestTeamData({(items:[TeamItem]) -> () in
//Getting the items from the API
})
EDIT 1
#objc final class TeamItem: Equatable, ResponseObjectSerializable, ResponseDictionarySerializable {
let firstName: String?
let lastName: String?
let seasonId: String?
let seasonName: String?
let teamId: String?
let teamName: String?
let rank: String?
let positionId: String?
let positionName: String?
let number: String?
let birthDate: String?
let birthPlace: String?
let citizenship: String?
let height: String?
let weight: String?
let maritalStatus: String?
let model: String?
let hobby: String?
let food: String?
let book: String?
let movie: String?
let wish: String?
let message: String?
let biography: String?
let imageURL: String?
let teamImageURL: String?
required init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.firstName = representation.valueForKeyPath(EndPoint.Keys.Team.FirstName.rawValue) as? String
self.lastName = representation.valueForKeyPath(EndPoint.Keys.Team.LastName.rawValue) as? String
self.seasonId = representation.valueForKeyPath(EndPoint.Keys.Team.SeasonId.rawValue) as? String
self.seasonName = representation.valueForKeyPath(EndPoint.Keys.Team.SeasonName.rawValue) as? String
self.teamId = representation.valueForKeyPath(EndPoint.Keys.Team.TeamId.rawValue) as? String
self.teamName = (representation.valueForKeyPath(EndPoint.Keys.Team.TeamName.rawValue) as? String)!
self.rank = representation.valueForKeyPath(EndPoint.Keys.Team.Rank.rawValue) as? String
self.positionId = representation.valueForKeyPath(EndPoint.Keys.Team.PositionId.rawValue) as? String
self.positionName = representation.valueForKeyPath(EndPoint.Keys.Team.PositionName.rawValue) as? String
self.number = representation.valueForKeyPath(EndPoint.Keys.Team.Number.rawValue) as? String
self.birthDate = representation.valueForKeyPath(EndPoint.Keys.Team.BirthDate.rawValue) as? String
self.birthPlace = (representation.valueForKeyPath(EndPoint.Keys.Team.BirthPlace.rawValue) as? String)!
self.citizenship = representation.valueForKeyPath(EndPoint.Keys.Team.Citizenship.rawValue) as? String
self.height = representation.valueForKeyPath(EndPoint.Keys.Team.Height.rawValue) as? String
self.weight = representation.valueForKeyPath(EndPoint.Keys.Team.Weight.rawValue) as? String
self.maritalStatus = representation.valueForKeyPath(EndPoint.Keys.Team.MaritalStatus.rawValue) as? String
self.model = representation.valueForKeyPath(EndPoint.Keys.Team.Model.rawValue) as? String
self.hobby = representation.valueForKeyPath(EndPoint.Keys.Team.Hobby.rawValue) as? String
self.food = representation.valueForKeyPath(EndPoint.Keys.Team.Food.rawValue) as? String
self.book = representation.valueForKeyPath(EndPoint.Keys.Team.Book.rawValue) as? String
self.movie = representation.valueForKeyPath(EndPoint.Keys.Team.Movie.rawValue) as? String
self.wish = representation.valueForKeyPath(EndPoint.Keys.Team.Wish.rawValue) as? String
self.message = representation.valueForKeyPath(EndPoint.Keys.Team.Message.rawValue) as? String
self.biography = representation.valueForKeyPath(EndPoint.Keys.Team.Biography.rawValue) as? String
self.imageURL = representation.valueForKeyPath(EndPoint.Keys.Team.ImageURL.rawValue) as? String
self.teamImageURL = representation.valueForKeyPath(EndPoint.Keys.Team.TeamImageURL.rawValue) as? String
}
#objc static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [TeamItem] {
var teamItemArray: [TeamItem] = []
if let representation = representation as? [[String: AnyObject]] {
for teamItemRepresentation in representation {
if let teamItem = TeamItem(response: response, representation: teamItemRepresentation) {
teamItemArray.append(teamItem)
}
}
}
return teamItemArray
}
}
func ==(lhs: TeamItem, rhs: TeamItem) -> Bool {
return lhs.lastName == rhs.lastName
}
}
EDIT
TeamItem.rank1 means actually that the value of the rank is 1 (the same for others)
This is what've need, hope will help someone:
#objc static func dictionary(#response: NSHTTPURLResponse, representation: AnyObject) -> [String: Array<TeamItem>] {
var teamItemDictionary: [String: Array<TeamItem>] = [:]
if let representation = representation as? [[String: AnyObject]] {
for teamItemRepresentation in representation {
if let teamItem = TeamItem(response: response, representation: teamItemRepresentation) {
if teamItem.rank != nil {
let teamKey = teamItem.teamId! + "-" + teamItem.rank!
if teamItem.teamId != EndPoint.Keys.Team.Type.rawValue {
if let team = teamItemDictionary[teamKey] as [TeamItem]? {
teamItemDictionary[teamKey]?.push(teamItem)
} else {
teamItemDictionary[teamKey] = []
teamItemDictionary[teamKey]?.push(teamItem)
}
}
} else {
if teamItem.teamId != EndPoint.Keys.Team.Type.rawValue {
if let team = teamItemDictionary[teamItem.teamId!] as [TeamItem]? {
teamItemDictionary[teamItem.teamId!]?.push(TeamItem)
} else {
teamItemDictionary[teamItem.teamId!] = []
teamItemDictionary[teamItem.teamId!]?.push(TeamItem)
}
}
}
}
}
}
return teamItemDictionary
}