UITableView не будет обновлять данные - PullRequest
0 голосов
/ 15 октября 2018

У меня есть ниже 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
}
}

edit:

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 голосов
/ 15 октября 2018

Вам нужно сделать что-то подобное в 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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...