UITableView не обновляет данные

У меня есть приведенный ниже 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
}
}

Что делает cell.configureCell ()?

onnoweb 15.10.2018 22:07

Смотрите редактирование, я добавил код для класса TableViewCell.

user440309 15.10.2018 22:14

Где устанавливается saleImage?

onnoweb 15.10.2018 22:16

Я установил его на раскадровке.

user440309 15.10.2018 22:19

Я бы ожидал, что где-нибудь в configureCell или в методе tableview.cellForItemAt будет оператор if, который может скрывать или показывать saleImage в зависимости от данных, которые вы получаете с вашего сервера. Где это?

onnoweb 15.10.2018 22:20
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
5
82
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 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
}

просто, но не думал об этом. именно то, что мне нужно! Большое спасибо!

user440309 15.10.2018 22:45

Рад, что это сработало для вас. Спасибо за отзыв :: Happy Coding!

Barns 15.10.2018 22:46

Другие вопросы по теме