I have an app with a CloudKit Public Database in which a CKRecord can contain a CKAsset or two that holds the url of image data. I don't want to always obtain the image data so my desiredKeys excludes the CKAsset key in the CKRecord in that case. I use the following Swift function.
var (matchResults, queryCursor) = try await database.records(matching: query, desiredKeys: desiredKeys)
The desiredKeys variable could be an array of strings with the keys of CKRecord fields I want to return or nil if I want all of the data including the asset data.
After I have the records, I do the following.
if let imageAsset = record["ImageAsset"] as? CKAsset,
let url = imageAsset.fileURL,
let data = try? Data(contentsOf: url) {
self.imageData = data
}
However, when I exclude the "ImageAsset" key from the desiredKeys array, my if let imageAsset contains the asset information. Looking at the received data, I can see that other keys that I exclude are not being downloaded, but the CKAsset url appears to be downloaded. Why? I expected that the if let would have been nil and the code within the if let would not have been executed.
The issue is fixed. What was the problem? I had another line of code following the records line in which I did not set desiredKeys. Here's the line of code.
let (continuingMatchResults, cMatchCursor) = try await database.records(continuingMatchFrom: queryCursor!)
Oince I changed it to
let (continuingMatchResults, cMatchCursor) = try await database.records(continuingMatchFrom: queryCursor!, desiredKeys: desiredKeys)
all was well.