0

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?

2
  • 1
    The //1 should be printed after //2, no? You are missing the asynchrone of perform(query:inZoneWith:completion:). You need to use yourself a closure. Commented May 4, 2022 at 20:43
  • Thank you @Larme , I definitely missed this, it's also my first time working with asynchrone calls. I'll read something about it and update this post as soon as I figured it out. Thank you so much for your help! Commented May 5, 2022 at 11:03

1 Answer 1

1

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)
      }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.