Home > Mobile >  CloudKit Data Sort Issues
CloudKit Data Sort Issues

Time:01-02

Not sure what I did wrong with this code but the sort on the data pull is not working with any of the data variables. I need to sort by name but right now it is sorted randomly.

func getStates(completionQueue: DispatchQueue = .main, completionHandler: @escaping (Result<[StateList], Error>) -> Void) {
    
    var fetchedStates: [StateList] = []
    
    let predicate = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "name", ascending: true)
    
    let query = CKQuery(recordType: "StateList", predicate: predicate)
    let queryOperation = CKQueryOperation(query: query)
    query.sortDescriptors = [sort]
    
    
    queryOperation.recordMatchedBlock = { (recordID, recordResult) in
        if let record = try? recordResult.get() as CKRecord {
            var stateList = StateList(recordID: record.recordID)
            stateList.recordID = record.recordID
            stateList.id = record["id"] as? String ?? ""
            stateList.name = record["name"] as? String ?? ""
            stateList.initial = record["initial"] as? String ?? ""
            
            fetchedStates.append(stateList)
            print(record.recordID)
        }
        print("recordMatchedBlock")
    }
    
    queryOperation.queryResultBlock = { result in
        DispatchQueue.main.async {
            switch result {
            case .success:
                completionHandler(.success(fetchedStates))
            case .failure(let error):
                completionHandler(.failure(error))
            }
        }
    }
    
    database.add(queryOperation)
}

CodePudding user response:

You have to put;

query.sortDescriptors = [sort]

before

let queryOperation = CKQueryOperation(query: query)

like this;

query.sortDescriptors = [sort]
let queryOperation = CKQueryOperation(query: query)
  • Related