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

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.

Related

How do I loop through a firestore document that has an array of maps?

I mostly work with dictionaries since I am fairly new but here we have an embedded struct that I need to loop through. With this, I need to be able to populate expanding cells in UITableView.
My struct looks like this:
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
}
And my query looks like this:
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let error = error {
print("error:\(error.localizedDescription)")
} else {
for document in documentSnapshot!.documents {
let eMail = document.get("E-mail")
let message = document.get("Message")
let timeStamp = document.get("Time_Stamp")
let userEmail = document.get("User_Email")
let planDetails = document.get("planDetails")
// how to loop through planDetails
}
}
I have gotten this far:
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let documentSnapshot = documentSnapshot {
for document in documentSnapshot.documents {
guard let planDetails = document.get("planDetails") as? [[String : Any]] else {
let email = document.get("E-mail")
let message = document.get("Message")
let timeStamp = document.get("Time_Stamp")
let userEmail = document.get("User_Email")
let status = false
}
for plan in planDetails {
if let menuItemName = plan["menuItemName"] as? String {
// not sure I populate the menuItemsName, menuItemsQuantity and menuItemsPrice within the array
}
}
}
}
}
UPDATE 2:
Final query: This is finally working as expected. But am not able to populate the expanding cells.
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let documentSnapshot = documentSnapshot {
for document in documentSnapshot.documents {
guard let planDetails = document.get("planDetails") as? [[String : Any]],
let email = document.get("E-mail") as? String,
let message = document.get("Message") as? String,
let timeStamp = document.get("Time_Stamp") as? String,
let userEmail = document.get("User_Email") as? String,
let status = document.get("status") as? Bool else {
continue
}
for plan in planDetails {
guard let menuItemName = plan["menuItemName"] as? String,
let menuItemQuantity = plan["menuItemQuantity"] as? Int,
let menuItemPrice = plan["menuItemPrice"] as? Double else {
continue
}
let planDetails = PlanDetails(menuItemName: menuItemName, menuItemQuantity: menuItemQuantity, menuItemPrice: menuItemPrice)
let complaint = Complain(eMail: email, message: message, timeStamp: timeStamp, userEmail: userEmail, status: status, planDetails: planDetails)
self.messageArray.append(complaint)
print(self.messageArray)
}
}
}
}
EDIT
// OPTION 1 - FULL REQUIREMENT
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let documentSnapshot = documentSnapshot {
for document in documentSnapshot.documents {
// all of these properties are required to parse a single document
guard let planDetails = document.get("planDetails") as? [[String : Any]],
let email = document.get("E-mail") as? String,
let message = document.get("Message") as? String,
let timeStamp = document.get("Time_Stamp") as? String,
let userEmail = document.get("User_Email") as? String,
let status = document.get("status") as? Bool else {
continue // continue this loop
}
for plan in planDetails {
// all of these properties are required to instantiate a struct
guard let name = plan["menuItemName"] as? String,
let price = plan["menuItemName"] as? Double,
let quantity = plan["menuItemQuantity"] as? Int else {
continue // continue this loop
}
let plan = PlanDetails(menuItemName: name, menuItemQuantity: quantity, menuItemPrice: price)
// then you will likely append this plan to an array
}
}
}
}
// OPTION 2 - PARTIAL REQUIREMENT
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let documentSnapshot = documentSnapshot {
for document in documentSnapshot.documents {
// all of these properties are required to parse a single document
guard let planDetails = document.get("planDetails") as? [[String : Any]],
let email = document.get("E-mail") as? String,
let message = document.get("Message") as? String else {
continue // continue this loop
}
// these properties are not required
let timeStamp = document.get("Time_Stamp") as? String // optional (can be nil)
let userEmail = document.get("User_Email") as? String // optional (can be nil)
let status = document.get("status") as? Bool ?? false // not optional because it has a default value of false
for plan in planDetails {
// all of these properties are required to instantiate a struct
guard let name = plan["menuItemName"] as? String,
let price = plan["menuItemName"] as? Double,
let quantity = plan["menuItemQuantity"] as? Int else {
continue // continue this loop
}
let plan = PlanDetails(menuItemName: name, menuItemQuantity: quantity, menuItemPrice: price)
// then you will likely append this plan to an array
}
}
}
}
There are a number of other ways you can do this, these are just a couple. For example, you can instantiate the struct with the [String: Any] dictionary itself.
I finally figured out what the problem was. Had to do with the way I setup the struct and how I populate the array.
Right way is as such i.e. the planDetails need to be cast as an array:
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
}
And then I need to iterate through each plan item, add it to the array and then add the array to the top level Complain:
db.collection("Feedback_Message").getDocuments() { documentSnapshot, error in
if let documentSnapshot = documentSnapshot {
for document in documentSnapshot.documents {
guard let planDetails = document.get("planDetails") as? [[String : Any]],
let email = document.get("E-mail") as? String,
let status = document.get("status") as? Bool else {
continue
}
for plan in planDetails {
guard let menuItemName = plan["menuItemName"] as? String,
let menuItemQuantity = plan["menuItemQuantity"] as? Int else {
continue
}
let singlePlan = PlanDetails(menuItemName: menuItemName, menuItemQuantity: menuItemQuantity)
self.planDetailsArray.append(singlePlan)
}
let complain = Complain(eMail: email, status: status, planDetails: self.planDetailsArray)
self.planDetailsArray.removeAll()
self.messageArray.append(complain)
}
}
// Print the main array or load table
}
}
bsod's answer stays as the correct answer because without his help, I would not have been able to arrive at his conclusion.

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.

Casting JSON array to a struct model swift

I am parsing a json array of object into a model which works. In this object, there is an array to a value and I created another model to handle that array but when ever I pass this object, the internal array returns nil after casting as the model class. Any help is appreciated
JSON Sample
[
{
"code": "AF",
"code3": "AFG",
"dial_code": "+93",
"name": "Afghanistan",
"capital": "Kabul",
"region": "Asia",
"subregion": "Southern Asia",
"states": [
{
"code": "BDS",
"name": "Badakhshān",
"subdivision": null
},
{
"code": "BGL",
"name": "Baghlān",
"subdivision": null
}
]
}
}
]
MODEL
public struct LocaleInfo {
public var locale: Locale?
public var id: String? {
return locale?.identifier
}
public var country: String
public var code: String
// public var phoneCode: String
public var states: [LocalStateInfo]
public var flag: UIImage? {
return UIImage(named: "Countries.bundle/Images/\(code.uppercased())", in: Bundle.main, compatibleWith: nil)
}
public var currencyCode: String? {
return locale?.currencyCode
}
public var currencySymbol: String? {
return locale?.currencySymbol
}
public var currencyName: String? {
guard let currencyCode = currencyCode else { return nil }
return locale?.localizedString(forCurrencyCode: currencyCode)
}
init(country: String, code: String/*, phoneCode: String*/, states: [LocalStateInfo]) {
self.country = country
self.code = code
self.states = states
self.locale = Locale.availableIdentifiers.map { Locale(identifier: $0) }.first(where: { $0.regionCode == code })
}
}
public struct LocalStateInfo {
public var code: String
public var name: String
public var subdivision: String
}
Passing the JSON Body
func getInfo(completionHandler: #escaping (FetchResults) -> ()) {
let bundle = Bundle(for: LocalePickerViewController.self)
let path = "Countries.bundle/Data/CountryCodes"
guard let jsonPath = bundle.path(forResource: path, ofType: "json"),
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else {
let error: (title: String?, message: String?) = (title: "ContryCodes Error", message: "No ContryCodes Bundle Access")
return completionHandler(FetchResults.error(error: error))
}
if let jsonObjects = (try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments)) as? Array<Any> {
var result: [LocaleInfo] = []
for jsonObject in jsonObjects {
guard let countryObj = jsonObject as? Dictionary<String, Any> else { continue }
guard let country = countryObj["name"] as? String,
let code = countryObj["code"] as? String/*,
let phoneCode = countryObj["dial_code"] as? String*/ else {
fatalError("Broken here")
continue
}
log("countryObj state \(countryObj["states"] as? [LocalStateInfo])", .fuck)
log("countryObj \(countryObj)", .fuck)
let states = countryObj["states"] as? [LocalStateInfo] ?? [LocalStateInfo]()
let new = LocaleInfo(country: country, code: code/*, phoneCode: phoneCode*/, states: states)
result.append(new)
}
return completionHandler(FetchResults.success(response: result))
}
let error: (title: String?, message: String?) = (title: "JSON Error", message: "Couldn't parse json to Info")
return completionHandler(FetchResults.error(error: error))
}
let states = countryObj["states"] as? [LocalStateInfo] ?? [LocalStateInfo]()
is presumably the line that isn't working for you. But countryObj is just a dictionary straight from JSON:
guard let countryObj = jsonObject as? Dictionary<String, Any> else { continue }
Why would casting it to an array of LocalStateInfo work at at all? It's an array of dictionaries, and you need to parse each one out individually.
You've said using Codable would alter the "entire scope" of the library, I don't understand how this is the case. You can implement codable (or even just Decodable) without affecting any other file.

keyNotFound(CodingKeys(stringValue: "coord", intValue: nil)

I am building a small swift weather app using the openweatherAPI and I am running into some issues trying to parse the JSON. I have used the following function to parse the get and parse the json.
Below is my weather data struct:
struct WeatherData: Codable {
let coord: Coord
let weather: [Weather]
let base: String
let main: Main
let visibility: Int
let wind: Wind
let clouds: Clouds
let dt: Int
let sys: Sys
let id: Int
let name: String
let cod: Int
}
struct Clouds: Codable {
let all: Int
}
struct Coord: Codable {
let lon, lat: Double
}
struct Main: Codable {
let temp: Double
let pressure, humidity: Int
let tempMin, tempMax: Double
enum CodingKeys: String, CodingKey {
case temp, pressure, humidity
case tempMin = "temp_min"
case tempMax = "temp_max"
}
}
struct Sys: Codable {
let type, id: Int
let message: Double
let country: String
let sunrise, sunset: Int
}
struct Weather: Codable {
let id: Int
let main, description, icon: String
}
struct Wind: Codable {
let speed: Double
let deg: Int
}
private func getWeatherData(url: String, parameters: [String : String]) {
let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]
print(JsonURLString)
let urlString = JsonURLString["url"] as? String
guard let url = URL(string: urlString!) else { return }
URLSession.shared.dataTask(with: url) { ( data, response, err ) in
DispatchQueue.main.sync {
if let err = err {
print("Failed to get data from url:", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let city = try decoder.decode(WeatherData.self, from: data)
self.weatherData.description = city.weather[0].description
self.weatherData.temperature = Int(city.main.temp - 273)
self.weatherData.city = city.name
self.weatherData.condition = city.weather[0].id
self.updateUIWeatherData()
} catch {
print(error)
self.cityLabel.text = "Connection issues"
}
}
}.resume()
}
The exact error I am getting is the following:
longitude = -0.1337, latitude = 51.50998
["parameters": ["lat": "51.50998", "long": "-0.1337", "appid": "xxxxxxxxxxxxxxxxxx"], "url": "https://api.openweathermap.org/data/2.5/weather"]
keyNotFound(CodingKeys(stringValue: "coord", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"coord\", intValue: nil) (\"coord\").", underlyingError: nil))
I have looked at the following example and don't see how this would apply. Any help would be appreciated.
Icon is not appearing. Here is my model:
import UIKit
class WeatherDataModel {
//Declare your model variables here
var temperature: Int = 0
var condition: Int = 0
var city: String = ""
var weatherIconName = ""
var description: String = ""
//This method turns a condition code into the name of the weather condition image
func updateWeatherIcon(condition: Int) -> String {
switch (condition) {
case 0...300 :
return "tstorm1"
case 301...500 :
return "light_rain"
case 501...600 :
return "shower3"
case 601...700 :
return "snow4"
case 701...771 :
return "fog"
case 772...799 :
return "tstorm3"
case 800 :
return "sunny"
case 801...804 :
return "cloudy2"
case 900...903, 905...1000 :
return "tstorm3"
case 903 :
return "snow5"
case 904 :
return "sunny"
default :
return "dunno"
}
}
}
I have added my own icons. I have added this in the do catch block.
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let city = try decoder.decode(WeatherData.self, from: data)
print(city)
self.weatherData.description = city.weather[0].description
self.weatherData.temperature = Int(city.main.temp - 273)
self.weatherData.city = city.name
self.weatherData.condition = city.weather[0].id
self.weatherData.weatherIconName = WeatherDataModel.updateWeatherIcon(self.weatherData.condition)
self.updateUIWeatherData()
} catch {
print(error)
self.cityLabel.text = "Connection issues"
}
The error I am getting this error now:
Instance member 'updateWeatherIcon' cannot be used on type 'WeatherDataModel'; did you mean to use a value of this type instead?
You are creating only the openweathermap URL but you ignore the parameters.
Use something like this for example URLComponents and URLQueryItem to build the URL query properly
private func getWeatherData(parameters: [String : String]) {
guard let lat = parameters["lat"],
let long = parameters["long"],
let appID = parameters["appid"] else { print("Invalid parameters"); return }
var urlComponents = URLComponents(string: "https://api.openweathermap.org/data/2.5/weather")!
let queryItems = [URLQueryItem(name: "lat", value: lat),
URLQueryItem(name: "lon", value: long),
URLQueryItem(name: "appid", value: appID)]
urlComponents.queryItems = queryItems
guard let url = urlComponents.url else { return }
URLSession.shared.dataTask(with: url) { ( data, response, err ) in
DispatchQueue.main.async { // never, never, never sync !!
if let err = err {
print("Failed to get data from url:", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let city = try decoder.decode(WeatherData.self, from: data)
print(city)
self.weatherData.description = city.weather[0].description
self.weatherData.temperature = Int(city.main.temp - 273)
self.weatherData.city = city.name
self.weatherData.condition = city.weather[0].id
self.updateUIWeatherData()
} catch {
print(error)
self.cityLabel.text = "Connection issues"
}
}
}.resume()
}
and pass only
["lat": "51.50998", "long": "-0.1337", "appid": "xxxxxxxxxxxxxxxxxx"]
as parameters.

How to map the nested data in a document from Firestore by 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?