从iCloud上下载公共数据

有两种方法,一种是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

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容