UITableView将不会更新数据

时间:2018-10-15 19:41:38

标签: ios swift uitableview cloudkit

我有下面的TableView显示产品和正在销售的产品。当产品开始销售时,它旁边会有一个图像。 问题是,当产品更新为销售时,CKSubscription通知会通过并得到处理(所有内容均正确到达ViewController中。

问题是,当第一个通知发出时,一切正常,但是在此之后,要销售的更新项目将不显示销售图像。这使我相信tableView的重新加载存在问题。

我还在tableView.reloadData()中尝试过.recordUpdated,但是它没有更新。委托和数据源已在情节提要中设置。我在做什么错??

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
 var array:[CKRecord] = []

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

     addNotificationObservers()
     getData()
}


@objc func getData() {
    self.array = []
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: “Product”, predicate: predicate)

    let queryOperation = CKQueryOperation(query: query)
    queryOperation.resultsLimit = 5
    queryOperation.qualityOfService = .userInitiated
    queryOperation.recordFetchedBlock = { record in
        self.array.append(record)
    }
    queryOperation.queryCompletionBlock = { cursor, error in
        if error != nil{
          print(error?.localizedDescription)

        }
        else{
            if cursor != nil {
                self.askAgain(cursor!)
            }
        }
        OperationQueue.main.addOperation {
            self.tableView.reloadData()
        }
    }
    Database.share.publicDB.add(queryOperation)
}

func askAgain(_ cursor: CKQueryOperation.Cursor) {
    let queryOperation = CKQueryOperation(cursor: cursor)
    queryOperation.resultsLimit = 5

    queryOperation.recordFetchedBlock = {
        record in
        self.array.append(record)
    }
    queryOperation.queryCompletionBlock = { cursor, error in
        if error != nil{
            (error?.localizedDescription)
        }
        else{
            if cursor != nil {
                self.askAgain(cursor!)
            }
        }
        OperationQueue.main.addOperation {
            self.tableView.reloadData()
        }
    }
    Database.share.publicDB.add(queryOperation)
}

  func addNotificationObservers() {
    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: CloudKitNotifications.NotificationReceived), object: nil, queue: OperationQueue.main) { (notification) in
        let notification = notification.object as! CKQueryNotification
        if let recordID = notification.recordID {
            switch notification.queryNotificationReason{
            case .recordCreated:
                Database.share.publicDB.fetch(withRecordID: recordID) { (record, error) in
                    if record != nil {
                        DispatchQueue.main.async {
                            self.tableView.beginUpdates()
                            self.array.insert(record!, at: 0)
                            let indexPath = NSIndexPath(row: 0, section: 0)
                            self.tableView.insertRows(at: [indexPath as IndexPath], with: .top)
                            self.tableView.endUpdates()
                        }
                    }
                }

            case .recordDeleted:
                DispatchQueue.main.async {
                    self.array = self.array.filter{ $0.recordID != recordID }
                    self.tableView.reloadData()
                }

            case .recordUpdated:
                Database.share.publicDB.fetch(withRecordID: recordID) { (record, error) in
                    if record != nil {

                  DispatchQueue.main.async {
                                    //gets the old record
                                    let getOldRecord = self.array.filter{ $0.recordID == recordID }
                               // gets position of old record
                                    let positionofOldRecord = self.array.firstIndex(of: getOldRecord[0])
                        print("here is the position of old record \(positionofOldRecord)")
                             //gets the array without the old record
                                    self.array = self.array.filter{ $0.recordID != recordID }

                                    //now go to the position of the old one and replace it with the new one
                                    var newArray = self.array

                            self.tableView.beginUpdates()
                            let indexPath = NSIndexPath(row: positionofOldRecord!, section: 0)
                            self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)
                            self.array.insert(record!, at: positionofOldRecord!)
                            self.tableView.insertRows(at: [indexPath as IndexPath], with: .automatic)
                            self.tableView.endUpdates()
                        }
                                           }
                 }

            default:
                break
            }
        }
    }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as? TableViewCell else { return UITableViewCell() }
    let item = array[indexPath.row]
    if item[“whatsTheNumber”] == 0 {
    cell.saleView.isHidden=true
    }
    cell.configureCell(brandBame: item[“Name”]!. productName: item[“ProductName”]!)

    return cell
}
}

编辑:

class TableViewCell: UITableViewCell {

@IBOutlet weak var brandNameLabel: UILabel!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var saleImage: UIImageView!
@IBOutlet weak var saleView: UIView!

func configureCell(brandName: String, productName:String){
    self.brandNameLabel.text = brandName
    self.productNameLabel.text = productName
}

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

1 个答案:

答案 0 :(得分:1)

您需要在cellForRowAt函数中执行以下操作:

 cell.configureCell(brandBame: item[“Name”]!, productName: item[“ProductName”]!, isSaleItem: item[“Sale”]!)

item[“Sale”]将是一个布尔标志

configureCell()函数中:

func configureCell(brandName: String, productName:String, isSaleItem: Bool){
    self.brandNameLabel.text = brandName
    self.productNameLabel.text = productName
    self.saleImage.isHidden = !isSaleItem
}