Невозможно загрузить данные iCloud в UITableView - PullRequest
0 голосов
/ 25 апреля 2019

Я пытаюсь следовать онлайн-учебнику, чтобы загрузить данные в iCloud и извлечь данные оттуда в мой tableView.Я следовал этому руководству, но по некоторым причинам я не могу загрузить данные в мое табличное представление.Я могу успешно загрузить данные в iCloud и запросить их, и после запроса я могу распечатать их.Не уверен, что я делаю неправильно.

Я написал функцию для запроса базы данных, но не уверен, почему данные не будут отображаться в tableView.

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    let database = CKContainer.default().privateCloudDatabase

    var notes = [CKRecord]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")

        refreshControl.addTarget(self, action: #selector(queryDatabase), for: .valueChanged)

        self.tableView.refreshControl = refreshControl
        queryDatabase()
    }

    @objc func queryDatabase() {
        let query = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
        database.perform(query, inZoneWith: nil) { (records, _) in

            guard let records = records else { return }
            print(records)
            let sortedRecords = records.sorted(by: {$0.creationDate! > $1.creationDate!})

            self.notes = sortedRecords
            DispatchQueue.main.async {
               self.tableView.reloadData()
               self.tableView.refreshControl?.endRefreshing()
            }
        }
    }
}

extension ViewController: UITableViewDataSource {

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let note = notes[indexPath.row].value(forKey: "content") as! String
        cell.textLabel?.text = note
        return cell
    }
}

КогдаЯ печатаю записи и получаю что-то вроде

[{creatorUserRecordID -> lastModifiedUserRecordID -> creationDate -> 2019-04-25 01:26:04 +0000 ModificationDate -> 2019-04-25 01:26: 04 +0000ifiedByDevice -> содержимое iPhone XR -> "HEllo"}, {creatorUserRecordID -> lastModifiedUserRecordID -> creationDate -> 2019-04-25 02:42:03 +0000 модификацияDate -> 2019-04-25 02:42: 03 +0000ifiedByDevice -> содержимое iPhone XR -> «Привет»}]

Я хотел загрузить все записи в моем tableView.

1 Ответ

0 голосов
/ 25 апреля 2019

Ваш ViewController имеет реализацию протокола UITableViewDataSource, но tableView не имеет dataSource.

tableView.reloadData() ничего не делает, потому что tableView не знает, какие данные должны быть загружены.

dataSource is The object that acts as the data source of the table view. https://developer.apple.com/documentation/uikit/uitableview/1614955-datasource

В этом вопросе добавление tableView.dataSource = self в viewDidLoad решает проблему.

Этот код указывает tableView загружать данные из ViewController.

Это не по теме, хотя строка let cell = UITableViewCell() создаст другую проблему.Узнайте, как повторно использовать UITableViewCell для повышения производительности tableView.

https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecell

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...