I really appreciate your help on this. I have searched the web for days for a solution but no luck so really thank you for your help. I'm also new to Swift coding so a lot of things not clear to me yet.
I built this app following source code of a similar app which is based on dictionary so it is best I keep this structure otherwise I will have to change pretty much everything which for me will be very confusing/messy.
You mentioned to add below code in Basket class. where exactly I need to add this line and any other code need changing there?
var itemIdAndQuantityMap: [String: Int] = [:]
below 2 functions I mentioned in my first post are written in ItemViewController separate from the Basket class.
@objc func addToBasketButtonPressed()
func incrementQty (basketId: String, itemToUpdate: String, deltaQty: Int)
below is everything I have in my Basket class. if you can tell me which line of code I should change/add for appending document "itemIds".
class Basket {
var id: String!
var ownerId: String!
var itemIds: [String]!
var delivery: Float!
var admin: Float!
var quantity: Int!
// var itemId: String
init() {
}
init(_dictionary: NSDictionary) {
id = _dictionary[kOBJECTID] as? String
ownerId = _dictionary[kOWNERID] as? String
itemIds = _dictionary[kITEMIDS] as? [String]
delivery = _dictionary[kDELIVERY] as? Float
admin = _dictionary[kADMIN] as? Float
quantity = _dictionary[kQUANTITY] as? Int
// itemId = _dictionary[kITEM] as? String
}
}
//MARK: - Download items
func downloadBasketFromFirestore(_ ownerId: String, completion: @escaping (_ basket: Basket?)-> Void) {
FirebaseReference(.Basket).whereField(kOWNERID, isEqualTo: ownerId).getDocuments { (snapshot, error) in
guard let snapshot = snapshot else {
completion(nil)
return
}
if !snapshot.isEmpty && snapshot.documents.count > 0 {
let basket = Basket(_dictionary: snapshot.documents.first!.data() as NSDictionary)
completion(basket)
} else {
completion(nil)
}
}
}
//MARK: - Save to Firebase
func saveBasketToFirestore(_ basket: Basket) {
FirebaseReference(.Basket).document(basket.id).setData(basketDictionaryFrom(basket) as! [String: Any])
}
//MARK: Helper functions
func basketDictionaryFrom(_ basket: Basket) -> NSDictionary {
return NSDictionary(objects: [basket.id, basket.ownerId, basket.itemIds,basket.quantity, basket.delivery, basket.admin], forKeys: [kOBJECTID as NSCopying, kOWNERID as NSCopying, kITEMIDS as NSCopying, kQUANTITY as NSCopying,kDELIVERY as NSCopying, kADMIN as NSCopying])
}
//MARK: - Update basket
func updateBasketInFirestore(_ basket: Basket, withValues: [String : Any], completion: @escaping (_ error: Error?) -> Void) {
FirebaseReference(.Basket).document(basket.id).updateData(withValues) { (error) in
completion(error)
}
}