昨天講完新增資料後,今天就來教大家如何用TableView顯示CloudKit Database中的資料吧!
首先,我們新增一個Struct,以便後續功能的操作
struct People {
var recordID : CKRecord.ID?
var name : String?
init(recordID:CKRecord.ID? = nil, name:String){
self.recordID = recordID
self.name = name
}
//將得到的record轉為上面宣告的struct型態回傳
static func fromRecord(_ record: CKRecord) -> People?{
guard let name = record.value(forKey: "name") as? String else{
return nil
}
return People(recordID: record.recordID, name: name)
}
}
並且在主畫面宣告一個People型態的空陣列
var nameArray = [People]()
接著利用fetch query的方式來撈取相對應的record,當成功時則會將撈到的record轉成People型態,新增至暫放資料的陣列再加至上面宣告的空陣列
func fetchItem(){
//暫放資料的陣列
var nameArray = [People]()
let query = CKQuery(recordType: "People", predicate: NSPredicate(value: true))
database.fetch(withQuery: query) { result in
switch result{
case .success(let result):
result.matchResults.compactMap { $0.1 }.forEach{
switch $0{
case .success(let record):
if let people = People.fromRecord(record){
nameArray.append(people)
}
case .failure(let error):
print(error)
}
}
self.nameArray = nameArray
DispatchQueue.main.async {
self.nameTableView.reloadData()
}
case .failure(let error):
print(error)
}
}
}
如此一來TableView便能成功顯示CloudKit Database的資料啦!
明天我們就來實作CloudKit Database的刪除功能吧!