Написал самое простецкое приложение с CloudKit.
Как сохранять значения разобрался, а как удалять все никак не пойму…
Насколько я понял нужно как-то получить значения CKRecordID они же уникальные Record name в Dashboard, но как не понятно.
Помогите пожалуйста разобраться!
import UIKit
import CloudKit
class TableViewController1: UITableViewController {
let database = CKContainer.default().privateCloudDatabase
var notes = [CKRecord]()
override func viewDidLoad() {
super.viewDidLoad()
queryDatabase()
self.tableView.reloadData()
}
@IBAction func onPlusTapped() {
let alert = UIAlertController(title: "Text", message: "", preferredStyle: .alert)
alert.addTextField { (textField) in textField.placeholder = ""
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let post = UIAlertAction(title: "Post", style: .default) { (_) in
guard let text = alert.textFields?.first?.text else { return }
self.saveToCloud(note: text)
}
alert.addAction(cancel)
alert.addAction(post)
present(alert, animated: true, completion: nil)
}
func saveToCloud(note: String) {
let newNote = CKRecord(recordType: "NoteM")
newNote.setValue(note, forKey: "content")
database.save(newNote) { (record, error) in
guard record != nil else { return }
print("Сохранение удалось!")
}
}
@objc func queryDatabase() {
let query = CKQuery(recordType: "NoteM", predicate: NSPredicate(value: true))
database.perform(query, inZoneWith: nil) { (records, _) in
guard let records = records else { return }
let sortedRecords = records.sorted(by: { $0.creationDate! > $1.creationDate! })
self.notes = sortedRecords
DispatchQueue.main.async {
self.viewDidLoad()
}
}
}
func deleteToCloud() {
let noteID = CKRecordID(recordName: "NoteM")
database.delete(withRecordID: noteID, completionHandler: { (noteID, error) in
guard noteID != nil else { return }
print("Удаление удалось")
})
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .default, title: "Удалить") { (action, indexPath) in
self.deleteToCloud()
}
delete.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
return [delete]
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {return 1}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let note = notes[indexPath.row].value(forKey: "content") as! String
cell.textLabel?.text = note
return cell
}
}