从CloudKit和Swift 3中的表/ RecordType计算字段的总和,比如Bill_Amount,用于特定的Customer_Name

时间:2017-07-26 15:42:11

标签: ios swift cloudkit

我在Cloudkit中有一个Sales表,它将Customer_Name和Bill_Amount作为单独的字段。如何计算所有客户的Bill_Amount值的总和并在UITableView中显示,如下所示?

    Sales from Customer
    ------------------------------------
    Customer_Name            Sales Amount
    ------------------------------------                        
    Customer A.               50,000                          
    Customer B.               30,000                
    Customer C.               60,000            
    Customer D.               50,000

在CloudKit中我有两个表:a)交易b)PartyAccounts。 PartyAccounts包含所有参与方详细信息。交易包含Txn_ID,Txn_Date,Party,Amount,Remarks。

我想在上面的UITableView中显示Summary,直到现在哪个派对有什么Balance。我尝试过很多东西,例如添加两个不同的数组,[String]代表派对名称,[Double]代表PartyBalances,当我点击为UITableView重新加载点击的viewAllTapped按钮而不是viewLoad事件时,所有数据都会加载。

我的代码是:

//
//  ViewController4.swift
//  General Ledger
//
//  Created by Aakash Vijay on 21/07/17.
//  Copyright © 2017 Aakash Vijay. All rights reserved.
//

    import UIKit
    import CloudKit
    import MobileCoreServices

    class ViewController4: UIViewController, UITableViewDelegate, UITableViewDataSource {
        var loadTransactionData = [CKRecord]()
        var partyAccountsData = [CKRecord]()
        let publicDB = CKContainer.default().publicCloudDatabase
        let cntr = CKContainer.default()
        typealias finshedFunction = () -> ()
        @IBOutlet weak var tableView: UITableView!
        @IBOutlet weak var view1: UIView!
        var partyNames : [String] = []
        var partyBalances : [Double] = []


        //viewAllTapped is Button That Reloads UITableView
        @IBAction func viewAllTapped(_ sender: UIButton) {        
            print(self.partyAccountsData.count)
            print(self.loadTransactionData.count)
            print(partyBalances.count)
            self.tableView.reloadData()
        }

        var ptyAmt : Double = 0.0
        var ptyNam : String = ""
        var tmpPty : String = ""


        override func viewDidLoad() {
            super.viewDidLoad()
            view1.layer.borderWidth = 1
            view1.layer.cornerRadius = 10
            tableView.layer.borderWidth = 1
            tableView.layer.cornerRadius = 10
            self.loadNewData()    /// Data Loaded(But Now Shown in TableView) i Don't know Why Sometimes executes full code and sometimes shows error.
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }


        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.partyAccountsData.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewPartyBalanceTVC
            cell.view2.layer.borderWidth = 1
            cell.view2.layer.cornerRadius = 10
            cell.nameLabel.text = String(self.partyAccountsData[indexPath.row].value(forKey: "Party_Name") as! String)
            cell.amountLabel.text = String(self.partyBalances[indexPath.row])
            return cell
        }
    /// Now partyAccountsData refers to all party
//////// loadNewData fills partyAccountsData with PartyAccounts Table's Data
        func loadNewData() {
            let qry = CKQuery(recordType: "PartyAccounts", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
            qry.sortDescriptors = [NSSortDescriptor(key: "Party_ID", ascending: true)]
            publicDB.perform(qry, inZoneWith: nil) { (results, error) in
                DispatchQueue.main.async {
                    if let rcds = results {
                        self.partyAccountsData = rcds
                        //self.tableView.reloadData()
                    }
                }
                if error != nil {
                    self.showAlert(msg: (error?.localizedDescription)!)
                }
            }

            let qry2 = CKQuery(recordType: "Transactions", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
            qry2.sortDescriptors = [NSSortDescriptor(key: "Party", ascending: true)]
            publicDB.perform(qry2, inZoneWith: nil) { (results, error) in
           ///// following code adds partyBalance ptyAmt to an array
                DispatchQueue.main.async {
                    if let rcds = results {
                        self.ptyAmt = 0
                        for i in 0..<self.partyAccountsData.count {
                            var str1 : String = ""
                            var str2 : String = ""
                            for z in 0..<rcds.count {
                                str1 = self.partyAccountsData[i].value(forKey: "Party_Name") as! String
                                str2 = rcds[z].value(forKey: "Party") as! String
                                if str1 == str2 {
                                    self.ptyAmt = self.ptyAmt + Double(rcds[i].value(forKey: "Amount") as! Double)
                                }
                            }
                            self.partyBalances.append(self.ptyAmt)
                            self.ptyAmt = 0
                        }
                        self.loadTransactionData = rcds
                        self.tableView.reloadData()
                    }
                    if error != nil {
                        self.showAlert(msg: (error?.localizedDescription)!)
                    }
                }
            }
        }
    /////// Code to show Alert
        func showAlert(msg: String)
        {
            let alert = UIAlertController(title: "CloudKit", message: msg, preferredStyle: .alert)
            let okButton = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
            alert.addAction(okButton)
            self.present(alert, animated: true, completion: nil)
        }
        var tData = [CKRecord]()

        func allDataFill() {
            let qry = CKQuery(recordType: "PartyLedger", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
            qry.sortDescriptors = [NSSortDescriptor(key: "Party_Name", ascending: true)]
            publicDB.perform(qry, inZoneWith: nil) { (results, error) in
                DispatchQueue.main.async {
                    if let rcds = results {
                        self.tData = rcds
                    }
                }
                if error != nil {
                    self.showAlert(msg: (error?.localizedDescription)!)
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我刚刚得到了解决方案。我做了以前相同但使用完成处理程序,它完美地工作。