0

Im working on an app where a merchant can add a bunch of products into a persons tab.

After selecting the customer from a table view the user can see a list of products and the total amount which I'd like to save under that customers name for him to come pay later. I've done a lot of research about relationships in CoreData but have not found a way to save many items at once.

Here is a screenshot of the view controller showing the customer and the products to add to his tab.

Add to tab view controller

I've created the data models and all and everything works great just can't link the products to each customer. I want to be able to click on a customer and see all the products in his tab. I've spent weeks now trying to find an answer and its getting very frustrating. Just need to be able to save and retrieve the items and my app will be done.

Really looking forward to an answer!

import UIKit
import MapKit
import GoogleSignIn
import CoreData

class addToTabViewController: UIViewController {

// Data Arrays
var myCart = [Cart]()
var myCartUz: [Cart] = []

var selectedIndex: Int!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

var amount: String = ""
var transaction: String = ""

@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var customerName: UILabel!
@IBOutlet weak var phoneNumber: UILabel!
@IBOutlet weak var emailAddress: UILabel!
@IBOutlet weak var customerAddress: UILabel! 
@IBOutlet weak var profileView: UIView!
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var receiptView: UIView!

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var customerProfile: UIImageView!
@IBOutlet weak var customerProfileView: UIView!
@IBOutlet weak var totalAmount: UILabel!
@IBOutlet weak var merchantName: UILabel!
@IBOutlet weak var merchatEmail: UILabel!

// Variable
var customers: Cutomers!

override func viewDidLoad() {
    super.viewDidLoad()

    // Show data
    configureEntryData(entry: customers)
    fetchCartData()
    totalAmount.text = amount

    // Design parameters
    hutzilopochtli()

}    

// Info profile button
@IBAction func infoButton(_ sender: Any) {
    profileView.isHidden = !profileView.isHidden
    receiptView.isHidden = !receiptView.isHidden
    customerProfileView.isHidden = !customerProfileView.isHidden
}

// Add to tab button
@IBAction func addToTabButton(_ sender: Any) {


}

// Show customer details
func configureEntryData(entry: Cutomers) {

    let name = entry.name
    let address = entry.address
    let phone = entry.phoneNumber
    let email = entry.email

    customerName!.text = name
    customerAddress!.text = address
    phoneNumber!.text = phone
    emailAddress!.text = email
    self.title = name

    let image = entry.profileicture as Data?
    profilePicture!.image =  UIImage(data: image!)
    customerProfile!.image = UIImage(data: image!)

}

// Get cart data
func fetchCartData() {

    do {
        myCart = try context.fetch(Cart.fetchRequest())
        myCartUz = myCart
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    } catch {

    }

    merchantName?.text = GIDSignIn.sharedInstance().currentUser.profile.name
    merchatEmail?.text = GIDSignIn.sharedInstance().currentUser.profile.email

}

// Design parameters function
func hutzilopochtli(){

profilePicture.roundMyCircle()
customerProfile.roundMyCircle()
profileView.layer.cornerRadius = 15
receiptView.layer.cornerRadius = 15
profileView.isHidden = true
map.layer.cornerRadius = 13    
}  
}

// Table view dataSource and delegates

 extension addToTabViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myCartUz.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "discountCell", for: indexPath) as! discountTableViewCell

    let price = myCartUz[indexPath.row].price
    let xNSNumber = price as NSNumber

    cell.productName?.text = myCartUz[indexPath.row].product
    cell.amountLabel?.text = "IDR \(xNSNumber.stringValue)"

    return cell
} 
}

Here is the customer class

class constantCustomer: NSObject {
    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext

    }

class func saveObject(customerId: String, name: String, phone: String, address: String, email: String, picture: NSData) -> Bool {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Cutomers", in: context)
    let managedObject = NSManagedObject(entity: entity!, insertInto: context)

    managedObject.setValue(customerId, forKey: "customerID")
    managedObject.setValue(NSDate(), forKey: "date")
    managedObject.setValue(name, forKey: "name")
    managedObject.setValue(phone, forKey: "phoneNumber")
    managedObject.setValue(address, forKey: "address")
    managedObject.setValue(email, forKey: "email")
    managedObject.setValue(picture, forKey: "profileicture")
    do {
        try context.save()
        return true
    } catch {
        return false
    }
}


class func fetchObject() -> [Cutomers]? {
    let context = getContext()
    var myCustomers: [Cutomers]? = nil

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Cutomers")
    let sort = NSSortDescriptor(key: "date", ascending: true)
    fetchRequest.sortDescriptors = [sort]

    do {
        myCustomers = try context.fetch(Cutomers.fetchRequest())
        return myCustomers
    } catch {
        return myCustomers
    }
}

}

1 Answers1

0

Without knowing about the Customers class I can only create an example. This is for the saving process:

func saveCustomer(entry: Customers) {
        let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: viewContext)
        let customer = Customers(entity: entity!, insertInto: viewContext)

        // add data to your customer class
        customer.price = price


        for journalEntry in entry.entry {
            /// Your class with the Relationship
            let persistent = CustomersDetail(context: viewContext)
            persistent.question = journalEntry.question
            persistent.answer = journalEntry.answer
            customer.addToRelationship(persistent)
        }
        /// do saving
        do {
            try viewContext.save()
        } catch let error {
            print(error.localizedDescription)
        }
    }

loading Customer for a specific CostumerName:

func loadCustomerData(customerName: String) -> Customers {
    let fetch:NSFetchRequest<Customers> = Customers.fetchRequest()

    fetch.predicate = NSPredicate(format: "customerName = %@", "\(customerName)")


    var customer = [Customers]()
    do {
        customer = try viewContext.fetch(fetch)
    } catch let error {
        print(error.localizedDescription)
    }
    return customer
}

enter image description here

PaFi
  • 888
  • 1
  • 9
  • 24