Reputation: 107
I'm trying to fetch some data from a private ClouKit database. The query and predicate is working fine because I can see at print(data) // 1
that the array is filled with all the data. But as soon as it leaves perform(){}
the array is resetted to it's at the top defined values and it just returns them.
func fetchUserRecord() -> [Double] {
var data: [Double] = [0, 1, 2] //demo data
let aWeekAgo = Date().addingTimeInterval(-604800)
let privateDB = CKContainer.default().privateCloudDatabase
let predicate = NSPredicate(format: "Date > %@", aWeekAgo as NSDate)
let query = CKQuery(recordType: "ProgressionValue", predicate: predicate)
privateDB.perform(query, inZoneWith: nil) { records, error in
guard let records = records else { return }
for record in records {
data.append(record["Value"] as! Double)
}
data.append(0.0)
print(data) // 1
}
print(data) // 2
return data
}
Here are the outputs:
print(data) //1: [0.0, 1.0, 2.0, {tons of doubles}, 0.0]
print(data) //2: [0.0, 1.0, 2.0]
What am I missing?
Upvotes: 0
Views: 406
Reputation: 2676
Try the new synch tools;
func fetchUserRecord() async throws -> [Double]
{
var data: [Double] = [0, 1, 2] // you don't really want the
let aWeekAgo = Date().addingTimeInterval(-604800)
let privateDB = CKContainer.default().privateCloudDatabase
let predicate = NSPredicate(format: "Date > %@", aWeekAgo as NSDate)
let query = CKQuery(recordType: "ProgressionValue", predicate: predicate)
let (values, cursor) = try await privateDB.records(matching: query, resultsLimit: 100)
for r in values
{
if let rec = try? r.1.get()
{
data.append(rec["value"] as Double)
}
}
return x
}
Call it like this;
Task
{
do {
data = try await fetchUserRecord()
}
catch
{
print(error)
}
}
Upvotes: 1