0

I've written this model swift file class and runs when calls without errors but doesn't fill any record field data into into the resultsValueArray array. What am I missing here?

import Foundation
import CloudKit

class TeamDataLoad {

let container = CloudKit.CKContainer(identifier: "ICloud.Brian-Naszradi.RosterTableView")

func rosterQuery(tName: String) -> Array<Any> {

var resultsValueArray = [] as Array
   
    let teamPredicate = NSPredicate(format: "teamName == %@", tName)
    print("teamPredicate: ", teamPredicate)
    
    
    let query = CKQuery(recordType: "team", predicate: teamPredicate)
    print("query: ", query)

    
    let qOperation = CKQueryOperation.init(query: query)

    qOperation.resultsLimit = 25

    qOperation.recordFetchedBlock = { record in
    
         let results = [record.value(forKey: "player") as! String]
        print("player is:", results)
         
        resultsValueArray.append(contentsOf: results)
       
        
         }  //recordFetchedBlock
    
      
    qOperation.queryCompletionBlock = { cursor, error in
        
      let queryCount = resultsValueArray.count
        
    } // qOperttion queryCompletionBlock
    
  CKContainer.default().publicCloudDatabase.add(qOperation)

  return resultsValueArray
    
  } //rosterQuery func


  }  // TeamDataLoad class

Any suggestions?

m2016b
  • 534
  • 5
  • 19
BrianN
  • 1
  • Where do you use the guy named container and where does publicCloudDatabase come from? – El Tomato Jan 03 '21 at 23:12
  • The container is used by the CKQuery, CKQueryOperation, etc and is executed with the CKContainer.default().publicCloudDatabase.add(qOperation) statement. The code does successfully query the iCloud database but I can't figure out why it won't fill the resultsValueArray? – BrianN Jan 05 '21 at 01:16
  • That's because `CKQueryOperation` works asynchronously? Use the completion block to wait for the result. – El Tomato Jan 05 '21 at 03:11
  • Thanks for pointing me in the right direction. The CKQueryOperation is asynchronous. Tried using the completion block but the class return still happened before the completion block executed. I added a counter just before the class return statement to wait for for the query operation to finish and the resultsValueArray did populate and pass successfully in the method call. Wondering if there is a better way to do this other than with a counter guessing for when the query operation completes? – BrianN Jan 06 '21 at 18:37

0 Answers0