CloudKit-不会更新(Swift)

时间:2016-05-09 01:04:30

标签: ios swift uitableview cloudkit

import UIKit
import CloudKit

class IdeaTableViewController: UITableViewController {

var posts = [CKRecord]()
var refresh:UIRefreshControl!

override func viewDidLoad() {
    super.viewDidLoad()
    refresh = UIRefreshControl()
    refresh.attributedTitle = NSAttributedString(string: "Pull to Refresh")
    refresh.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
    self.tableView.addSubview(refresh)
    loadData()
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return posts.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    if posts.count == 0{
        return cell
        print("zero Posts")
    }
    let post = posts[indexPath.row]

    if let postContent = post["content"] as? String{
        let dateFormat = NSDateFormatter()
        dateFormat.dateFormat = "MM/dd/yyyy"
        let dateString = dateFormat.stringFromDate(post.creationDate!)
        print("trying to Write the Post...")
        cell.textLabel?.text = "\(postContent)"
        cell.detailTextLabel?.text = "\(dateString)"

    }

    return cell
}

func loadData(){
    posts = [CKRecord]()
    let publicData = CKContainer.defaultContainer().publicCloudDatabase
    let query = CKQuery(recordType: "Post", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    publicData.performQuery(query, inZoneWithID: nil) { (results:[CKRecord]?, error:NSError?) -> Void in
        if let posts = results{
            self.posts = posts
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
                self.refresh.endRefreshing()
            })
        }
    }

}

@IBAction func add(sender: AnyObject) {
    let alert = UIAlertController(title: "New Idea", message: "Tell us what you're thinking.", preferredStyle: .Alert)
    alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in
        textField.placeholder = "Idea"
    }
    alert.addAction(UIAlertAction(title: "Post", style: .Default, handler: { (action: UIAlertAction) -> Void in

        let textField = alert.textFields!.first!

        if textField.text != ""{

            let newPost = CKRecord(recordType: "Post")
            newPost["content"] = textField.text
            let publicData = CKContainer.defaultContainer().publicCloudDatabase
            publicData.saveRecord(newPost, completionHandler: {(
                record:CKRecord?, error:NSError?) -> Void in
                if error == nil{
                    print("Post Saved")
                    dispatch_async(dispatch_get_main_queue(), {() -> Void in
                        self.tableView.beginUpdates()
                        self.posts.insert(newPost, atIndex: 0)
                        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
                        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
                        self.tableView.endUpdates()
                    })
                }else{
                    print("Post ERROR")
                    print(ErrorType)
                }
            })

        }

    }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)
  }


}

当我发布某些内容时我的表格应该更新时,它什么也没做。我不知道我是不是写了一个错误的错误。帖子出现在云套件iCloud在线但不在我的表中,即使在我刷新它之后。

1 个答案:

答案 0 :(得分:0)

虽然您正在使用CKDatabaseperformQuery便捷方法,但您可能会遇到CKQueryOperation中警告所描述的相同情况。recordFetchedBlock:< / p>

  

查询索引是异步更新的,因此无法保证它们是最新的。如果查询最近更改的记录并且没有足够的时间处理这些更改,则查询结果可能不正确。结果可能不包含正确的记录,记录可能不正常。

来源: CKQueryOperation Class Reference

this answer to another question中描述了一种解决方法:

  

如果您正在使用CKQuery来支持视图,那么您将要保留已在本地修改的记录的边表,并将这些记录组合到视图中,直到查询开始返回该记录。