Search code examples
c#xamarin.iosicloudcloudkitkey-value-store

Xamarin.iOS/How to retrieve a record from CloudKit by using only the Key


I was reading the Xamarin iOS documentation about CloudKit but it seems is not clear enough how to get the values of a specific record.

In the code below is what the documentation says how to fetch a record by using the "RecordID" but the recordID is generated on the cloudKit so I can't know the ID. `

// Create a record ID and fetch the record from the database
var recordID = new CKRecordID("MyRecordName");
ThisApp.PublicDatabase.FetchRecord(recordID, (record, err) => {
    // Was there an error?
    if (err != null) {
        ...
    }
});

`

I tried to use a Query to fetch a record by using the "Key" and the "Value" as the documentation suggest like this NSPredicate.FromFormat(string.Format("{0} = '{1}'", key, value)), which it works only because I know both the Key and Value, but in the production mode all I know is the "Key", the "Value" it will be generated and saved on the icloud.

An alternative solution that I can think is to retrieve all records for a specific reference type and from there find the one that I want by using the "Key" but I'm not sure what "NSPredicate" command should I use to retrieve all.


Solution

  • So I finaly figured it out how to solve the issue.

    My alternative thought was to retrieve all records for a specific reference type, which I achieved that by using the following "NSPredicate"

    var predicate = NSPredicate.FromValue(true);
    var query = new CKQuery(recordType, predicate);
    var result = await PublicDatabase.PerformQueryAsync(query, CKRecordZone.DefaultRecordZone().ZoneId);
    

    This will return a CKRecord[] array including all of my saved records.

    Finaly I loop throught the array and use my "Key" to check which record has a value like this

    string ret = "";
    for(nint i = 0; i < result.Length; ++i)
    {
        var record = (CKRecord)result[i];
        var recordValue = record.ValueForKey((NSString)MyKey);
        if (recordValue == null) continue;
        if(!string.IsNullOrEmpty(recordValue))
            return ret = recordValue;
    }