有两种方法,一种是convenience API,另一种是operational API。但是convenience API会一次性把单元内所有数据下载下来,数据量不大可以用。 建议用operational API
import UIKit
import CloudKit
class DiscoverTableViewController: UITableViewController {
var restaurants:[CKRecord] = []
override func viewDidLoad() {
super.viewDidLoad()
getRecordsFromCloud()
}
func getRecordsFromCloud() {
// Fetch data using Convenience API
let cloudContainer = CKContainer.defaultContainer()
let publicDatabase = cloudContainer.publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Restaurant", predicate: predicate)
publicDatabase.performQuery(query, inZoneWithID: nil, completionHandler: {
(results, error) -> Void in
if error != nil {
print(error)
return
}
if let results = results {
print("Completed the download of Restaurant data")
self.restaurants = results
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.tableView.reloadData()
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
return restaurants.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",
forIndexPath: indexPath)
// Configure the cell...
let restaurant = restaurants[indexPath.row]
cell.textLabel?.text = restaurant.objectForKey("name") as? String
if let image = restaurant.objectForKey("image") {
let imageAsset = image as! CKAsset
cell.imageView?.image = UIImage(data: NSData(contentsOfURL:
imageAsset.fileURL)!)
}
return cell
}
}