iosswift3cloudkitpass-datackrecord

How to pass the CloudKit records data from "TableView-Controller B" to "View-Controller C"?


I've got records data from my CloudKit and show on TableViewController-B successfully, but how can i pass the CloudKit's records(strings, images) to next ViewController-C?? ps. not tableViewcontroller-C

my first 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]       
                }

My 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   
    }


}

I useing the var DisData to get the CKRecord from tableViewController-B but it is not working by the method DisData?.object(forKey: "name") as? String and the image also can't figure out how to show it. Should I use the UITableViewController-B's func recordsFromCloud in ViewController-C again??? or any other smart way to get the Cloudkit's records, please help.


Solution

  • Make a variable named selectedRecord

    var selectedRecord: CKRecord!
    

    add the delegate method didSelectRowatindexPath

    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: IndexPath) {
    
        selectedRecord = myclouds[indexPath.row]
    performSegueWithIdentifier("showDetailSegue", sender: nil)
    
    }
    

    Change the prepareforsegue to this

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

    Change the type of DisData from CKRecord? to CKRecord! in showDetailVC

    var DisData: CKRecord!
    

    if you want to get your keys, declare the queryOperation outside the recordsFromCloud()

    Then, make a variable forKeys in showDetailVC

    var forKeys: [String]!
    

    and add the following line to prepareforsegue

    toDetailVC.forKeys = queryOperation.desiredKeys