如何将CloudKit记录数据从“TableView-Controller B”传递到“View-Controller C”?

时间:2017-07-01 20:15:21

标签: ios swift3 cloudkit pass-data ckrecord

我已经从CloudKit获取了记录数据并成功显示在TableViewController-B,但我怎样才能将CloudKit's records(strings, images)传递给下一个ViewController-Cps. not tableViewcontroller-C

我的第一个TableViewController-B

import UIKit  
import CloudKit  

class BTableViewControoler: UITableViewController {
       var myclouds:[CKRecord] = []
       var imageCache = NSCache<CKRecordID, NSURL>()
       var recordType: String!

    override func viewDidLoad() {
            super.viewDidLoad()

            recordsFromCloud()
        }

func recordsFromCloud() {

    let cloudContainer = CKContainer.default()
     let publicDatabase = cloudContainer.publicCloudDatabase  
        let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: recordType, predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        let queryOperation = CKQueryOperation(query: query)

        queryOperation.desiredKeys = ["name", "address", "GpNumber"]
        queryOperation.queuePriority = .veryHigh
        queryOperation.resultsLimit = 50
        queryOperation.recordFetchedBlock = { (record) -> Void in
            self.myclouds.append(record)
        }

        queryOperation.queryCompletionBlock = { (cursor, error) -> Void in
            if let error = error { print("Failed data - \(error.localizedDescription)")
                 return }
        print("Successfully data")  
        }
        publicDatabase.add(queryOperation)     
    }//fetchRecords End

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return myclouds.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MainCell


        let newInFo = myclouds[indexPath.row]

        cell.mainLabel.text = newInFo.object(forKey: "name") as? String
        cell.mainNumber.text = newInFo.object(forKey: "GpNumber") as? String
        cell.mainLocation.text = newInFo.object(forKey: "address") as? String
        cell.mainImage.image = UIImage(named: "photoalbum")

        //get image
        if let imageFileURL = imageCache.object(forKey: myclouds.recordID) {

            if let imageData = try? Data.init(contentsOf: imageFileURL as URL){
                cell.mainImage?.image = UIImage(data: imageData)
                }
            }else{

                let publicDatabase = CKContainer.default().publicCloudDatabase
                let fetchRecordsImageOperation =   CKFetchRecordsOperation(recordIDs: [newInFo.recordID])
                fetchRecordsImageOperation.desiredKeys = ["image"]
                fetchRecordsImageOperation.queuePriority = .veryHigh

                fetchRecordsImageOperation.perRecordCompletionBlock = {
                    (record, recordID, error) -> Void in

                    if let error = error {
                        print("Failed image:\(error.localizedDescription)")
                        return
                    }

                    if let newinfoRecord = record {
                        OperationQueue.main.addOperation() {
                    if let image = newinfoRecord.object(forKey: "image") {
                                let imageAsset = image as! CKAsset


                    if let imageData = try? Data.init(contentsOf: imageAsset.fileURL) {
                                    cell.mainImage.image = UIImage(data: imageData)
                                }

             self.imageCache.setObject(imageAsset.fileURL as NSURL, forKey: newInFo.recordID)

                            }
                         }
                    }//record end
                  }

             publicDatabase.add(fetchRecordsImageOperation)
          }//else end

          return cell
          }//cell end


//Segue To Next View 
       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "showDetailSegue" {
                if let indexPath = tableView.indexPathForSelectedRow {
                   let toDetailVC = segue.destination as! showDetailVC
                        toDetailVC.DisData = newinfo[indexPath.row]       
                }

我的ViewController-C

import UIKit
import CloudKit

class showDetailVC: UIViewController {

    @IBOutlet weak var detailpic: UIImageView!

    @IBOutlet weak var containerView: UIView!

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var infoLabel: UILabel!
    @IBOutlet weak var mynumberLabel: UILabel!

    var DisData: CKRecord?
    var getType: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        detailpic.image = UIImage(named: "photoalbum")
        infoLabel.text = DisData?.object(forKey: "address") as? String
        nameLabel.text = DisData?.object(forKey: "name") as? String
        mynumberLable.text = DisData?.object(forKey: "GpNumber") as? String   
    }


}

我使用var DisDataCKRecord获取tableViewController-B 但它没有按方法DisData?.object(forKey: "name") as? String工作 而且图像也无法弄清楚如何显示它。 我应该再次使用UITableViewController-B's中的func recordsFromCloud ViewController-C ???或任何其他聪明的方式获得Cloudkit's records,请帮助。

1 个答案:

答案 0 :(得分:2)

创建一个名为selectedRecord的变量

var selectedRecord: CKRecord!

添加委托方法didSelectRowatindexPath

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: IndexPath) {

    selectedRecord = myclouds[indexPath.row]
performSegueWithIdentifier("showDetailSegue", sender: nil)

}

将prepareforsegue更改为此

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                if segue.identifier == "showDetailSegue" {
                       let toDetailVC = segue.destination as! showDetailVC
                            toDetailVC.DisData = selectedRecord       
                    }

CKRecord?

中将DisData的类型从CKRecord!更改为showDetailVC
var DisData: CKRecord!

如果您想获取密钥,请在queryOperation 之外声明recordsFromCloud()

然后,在showDetailVC

中为凯斯创建一个变量
var forKeys: [String]!

并将以下行添加到prepareforsegue

toDetailVC.forKeys = queryOperation.desiredKeys