Getting an array of objects using FirebaseFirestoreSwift - swift

I have a struct that looks like this:
struct Joint: Identifiable, Codable {
#DocumentID var id : String? = UUID().uuidString
var serviceType : Int
var businessName : String
var keywords: [String]
var menu : [DishItems]
enum CodingKeys : String, CodingKey {
case businessName
case serviceType = "jointType"
case keywords
case menu
}
}
struct DishItems: Codable {
var listOrder : Int
var menuItemName : String
var menuItemDescription : String
var menuItemPrice : Double
}
The DishItems is a custom object and I am using FirebaseFireStoreSwift JSON decoder to retrieve the documents.
let db = Firestore.firestore().collection("Joints")
db.getDocuments { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No restaurants")
return
}
let jointsArray : [Joint] = documents.compactMap {
return try? $0.data(as: Joint.self)
}
completion(jointsArray)
}
I am able to query all of the documents if I exclude "menu" from the parent struct but as soon as I include it, then nothing is queried. How do I go about obtaining the array of objects inside the JSON?

Related

Need acces from document to collection Firestore

I'm trying to do an iOS app and i've binded it with firebase, so I'm trying to get some posts ad fetch them, and this works fine, however this posts got 2 collections (likes and replies) and i'm trying to fetch likes, the thing is that I can't get the likes because for some reasons I can't a class for document forEach neither I can't access it, someone got any idea?
Code:
import Foundation
import Firebase
struct Post : Hashable {
var id : String
var dateAdded : String
var posterEmail : String
var posterUsername : String
var posterIcon : String
var postTitle : String
var postBody : String
var likes : [String]
var userLikedPost : Bool
}
struct Like {
var likeId : String
var likerEmail : String
}
class Likes {
var likes : [Like] = []
func fetchLikes() {
//Firestore.firestore()
}
}
class Posts : ObservableObject {
#Published var posts : [Post] = []
func fetchPosts() {
Firestore.firestore().collection("posts").getDocuments(completion: { (docPosts, error) in
if (error != nil) {
print("error fetching posts")
} else {
docPosts?.documents.forEach { (post) in
let id = post.documentID
let email = post.get("posterEmail") as! String
let username = post.get("posterUsername") as! String
let icon = post.get("posterIcon") as! String
let title = post.get("title") as! String
let body = post.get("body") as! String
// Here i want to insert the code that gets the likes class and access the likes variable
self.posts.append(Post(id: id, dateAdded:String(id.split(separator: "_").joined(separator: "/").prefix(10)) ,posterEmail: email, posterUsername: username, posterIcon: icon, postTitle: title, postBody: body,
likes: [],userLikedPost: false))
}
}
})
}
}
The Firestore structure was not included in the question so I will present one for use
user_wines
uid_0
name: "Jay"
favorite_wines:
0: "Insignia"
1: "Scavino Bricco Barolo"
2: "Lynch Bages"
uid_1
name: "Cindy"
favorite_wines
0: "Palermo"
1: "Mercury Head"
2: "Scarecrow"
And then the code to read all of the user documents, get the name, the wine list (as an array as Strings) and output it to console
func readArrayOfStrings() {
let usersCollection = self.db.collection("user_wines")
usersCollection.getDocuments(completion: { snapshot, error in
guard let allDocs = snapshot?.documents else { return }
for doc in allDocs {
let name = doc.get("name") as? String ?? "No Name"
let wines = doc.get("favorite_wines") as? [String] ?? []
wines.forEach { print(" ", $0) }
}
})
}
and the output
Jay
Insignia
Scavino Bricco Barolo
Lynch Bages
Cindy
Palermo
Mercury Head
Scarecrow
EDIT
Here's the same code using Codable
class UserWineClass: Codable {
#DocumentID var id: String?
var name: String
var favorite_wines: [String]
}
and the code to read data into the class
for doc in allDocs {
do {
let userWine = try doc.data(as: UserWineClass.self)
print(userWine.name)
userWine.favorite_wines.forEach { print(" ", $0) }
} catch {
print(error)
}
}

How to get firebaseData into class/Struct and perform query operation

Firebase Realtime db Json
In my code:
contain("University_1") is any way to get character search so i can get university_1 data only
I need class/Struct to store all [data] down below
Code:
let ref = Database.database().reference()
ref.child("chat").child("Student_2-University_1").observeSingleEvent(of: .value, with: { (snapshot) in
for child in (snapshot.children.allObjects as! [DataSnapshot]) {
if (child.key.contains("user2")){
print(child.value(forKey: "university_id"))
// print(child)
}
}
})
my struct look like
struct ChatModel {
let lastMessage : LastMesage
let user1 : StudentData
let user2 : UniversityData
struct LastMesage{
let lastMsg : String
let sendBy: String
let time: Int
}
struct StudentData {
let student_id, student_name: String
}
struct UniversityData {
let university_id, university_name: String
}
}

Nil data returned when copying "working" json data to new struc array

Weird. I swear this was working but then it just stopped working .. or ... Please ignore the i+i ,I will clean this up...
I don't have a clue why but myrecords?[i].title is returning nil. The json.releases[i].date_adde is working fine and full of data. I can "print" it and get a result. but when I go to copy it to the myrecords it is returning nil.
I download the data from JSON, that works fine. then I try to copy the data to a struc array I can get to in other parts of my app and now my myrecords data is empty. what the heck am I doing wrong?
import Foundation
var numberOfRecords : Int = 0
struct routine {
var dateadded : String
var title : String
var artist : String
var year : Int
var recordlabel : String
}
var myrecords: [routine]?
//-------------------------------------------------------------
struct Response: Codable {
var pagination: MyResult
var releases: [MyReleases]
}
public struct MyResult: Codable {
var page: Int
var per_page: Int
var items: Int
}
public struct MyReleases: Codable {
var date_added: String
var basic_information: BasicInformation
}
public struct BasicInformation: Codable {
var title: String
var year: Int
var artists : [Artist]
var labels: [Label]
}
public struct Artist: Codable {
var name: String
}
public struct Label: Codable {
var name: String
}
let url = "https://api.discogs.com/users/douglasbrown/collection/folders/0/releases?callback=&sort=added&sort_order=desc&per_page=1000"
public func getData(from url: String) {
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("something went wrong")
return
}
//HAVE DATA
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch {
print("Converion Error:\(error.localizedDescription)")
}
guard let json = result else {
return
}
numberOfRecords = json.pagination.items
var i: Int
i = -1
for _ in json.releases {
i = i + 1
myrecords?[i].dateadded = json.releases[i].date_added
myrecords?[i].title = json.releases[i].basic_information.title
myrecords?[i].artist = json.releases[i].basic_information.artists[0].name
myrecords?[i].year = json.releases[i].basic_information.year
myrecords?[i].recordlabel = json.releases[i].basic_information.labels[0].name
print(">>>>>>\(myrecords?[i].dateadded)")
}
})
task.resume()
}
You haven't initialized myrecords array.
Otherwise, you cannot use subscript like myrecords[i] when you don't know the capacity of array, it can be out of index.
First, initialize your array.
var myrecords: [routine]? = []
Second, append new element to array instead of using subscript
for _ in json.releases {
let newRecord = routine()
newRecord.dateadded = json.releases[i].date_added
newRecord.title = json.releases[i].basic_information.title
newRecord.artist = json.releases[i].basic_information.artists[0].name
newRecord.year = json.releases[i].basic_information.year
newRecord.recordlabel = json.releases[i].basic_information.labels[0].name
myrecords.append(newRecord)
}
This is the answer. :) THANK YOU All for pointing me in the right direction
struct Routine {
var dateadded : String
var title : String
var artist : String
var year : Int
var recordlabel : String
}
var myRecords: [Routine] = []
var i : Int
i = -1
for _ in json.releases {
var newRecord = Routine.self(dateadded: "", title: "", artist: "", year: 0, recordlabel: "")
i = i + 1
newRecord.dateadded = json.releases[i].date_added
newRecord.title = json.releases[i].basic_information.title
newRecord.artist = json.releases[i].basic_information.artists[0].name
newRecord.year = json.releases[i].basic_information.year
newRecord.recordlabel = json.releases[i].basic_information.labels[0].name
myRecords.append(newRecord)
}
print(">>>>\(myRecords[0].dateadded)")
I will clean up the bad code too but it works and that is good! :)

Trouble with embeddd Codable objects and Firestore in SwiftUI

I have the following
class OrderBasket: Identifiable, Codable {
#DocumentID var id: String!
var credits: Int! = 200
var basketTotal: Int
var orderLines: [OrderLine] = []
enum CodingKeys: String, CodingKey {
case id
case credits
case basketTotal
case orderLines
}
}
and
class OrderLine: Identifiable, Equatable, Codable {
#DocumentID var id: String! = UUID ().uuidString
var sku : String!
var quantity : Int
var lineTotal: Int
enum CodingKeys: String, CodingKey {
case id
case sku
case quantity
case lineTotal
}
}
I am able to successfully read the data from Firestore. However, how do I extract the orderLines?
The following code works to read the OrderBasket. How do I get the orderLines?
db.collection("Basket").document(Auth.auth().currentUser!.uid).addSnapshotListener { (querySnapshot, error) in
guard let basket = querySnapshot?.data() else {
print("No documents for basket")
return
}
self.orderBasket.credits = (basket["credits"] as! Int)
self.orderBasket.basketTotal = basket["basketTotal"] as! Int
}
basket["orderLines"] contains the data but how do I get it to the object?
I am using FirebaseFirestoreSwift BTW.

Decode Json Data using JsonDecoder and Alamofire

I am trying decode Json data into my Model.
This is my model
struct Devices : Codable {
var id :String?
var description :String?
var status : Int?
}
var heroes = Devices()
print(DeviceId)
let loginParam: [String: Any] = [
"id": DeviceId
]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 5
manager.request("http://13.13.13.004/website/api/Customer/DeviceControl", method: .post , parameters: loginParam, encoding: JSONEncoding.prettyPrinted)
.responseData { response in
let json = response.data
do{
let decoder = JSONDecoder()
//using the array to put values
heroes = try decoder.decode(Devices.self, from: json!)
}catch let err{
print(err)
}
this code doesn't get in catch block.
But heroes values return nill.
When ı try use NsDictionary
Its give result.
This is a common mistake: You forget the root object
struct Root : Decodable {
private enum CodingKeys: String, CodingKey { case resultCount, devices = "results" }
let resultCount : Int
let devices : [Device]
}
And name the device struct in singular form (devices is an array of Device instances) and declare the members as non-optional
struct Device : Decodable {
var id : String
var description : String
var status : Int
}
...
var heroes = [Device]()
...
let result = try decoder.decode(Root.self, from: json!)
heroes = result.devices