Swift - Get all records from Cloudkit Public Database












0















Hi i'm trying to fetch all records from my publicDB in cloudkit, and currently there are more of 2000 records. How can I fetch them all and put them in an array?
I've tryed these two methods without success. Can you please help me?



1 Approach



    let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Position", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in

if error != nil {

DispatchQueue.main.async(execute: { () -> Void in
self.delegate?.errorUpdating(error: error! as NSError)
return
})
} else {
self.positionArray.removeAll(keepingCapacity: true)

for record in results! {

let position = Position(record: record as CKRecord, database: self.publicDB)
self.positionArray.append(position)

}
}

DispatchQueue.main.async(execute: { () -> Void in
/* my elaboration with the complete result */
})



}


2 Approach



    let predicate = NSPredicate(value: true)   
let query = CKQuery(recordType: "Position", predicate: predicate)

query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

let qop = CKQueryOperation(query: query)

qop.resultsLimit = 3000
qop.recordFetchedBlock = { (record: CKRecord) in
let position = Position(record: record, database: self.publicDB)
self.positionArray.append(position)
print(self.positionArray.count)
}

qop.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) in
DispatchQueue.main.async(execute: { () -> Void in
if let cursor = cursor {

print("entro")
let newOperation = CKQueryOperation(cursor: cursor)

newOperation.recordFetchedBlock = qop.recordFetchedBlock
newOperation.queryCompletionBlock = qop.queryCompletionBlock
self.publicDB.add(newOperation)
}

else if let error = error {
print("Error:", error)
}
// No error and no cursor means the operation was successful
else {
print("Finished with records:", self.positionArray)
if(!all){
// my elaboration
}
else{
// my elaboration
}
}
})
}

self.publicDB.add(qop)


With the first approach I can fetch at most 100 records.
With the second approach I can fetch at most 400 records.
But i need to fill my array with the all over 2000 records, how can achieve the result?










share|improve this question



























    0















    Hi i'm trying to fetch all records from my publicDB in cloudkit, and currently there are more of 2000 records. How can I fetch them all and put them in an array?
    I've tryed these two methods without success. Can you please help me?



    1 Approach



        let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Position", predicate: predicate)
    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in

    if error != nil {

    DispatchQueue.main.async(execute: { () -> Void in
    self.delegate?.errorUpdating(error: error! as NSError)
    return
    })
    } else {
    self.positionArray.removeAll(keepingCapacity: true)

    for record in results! {

    let position = Position(record: record as CKRecord, database: self.publicDB)
    self.positionArray.append(position)

    }
    }

    DispatchQueue.main.async(execute: { () -> Void in
    /* my elaboration with the complete result */
    })



    }


    2 Approach



        let predicate = NSPredicate(value: true)   
    let query = CKQuery(recordType: "Position", predicate: predicate)

    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let qop = CKQueryOperation(query: query)

    qop.resultsLimit = 3000
    qop.recordFetchedBlock = { (record: CKRecord) in
    let position = Position(record: record, database: self.publicDB)
    self.positionArray.append(position)
    print(self.positionArray.count)
    }

    qop.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) in
    DispatchQueue.main.async(execute: { () -> Void in
    if let cursor = cursor {

    print("entro")
    let newOperation = CKQueryOperation(cursor: cursor)

    newOperation.recordFetchedBlock = qop.recordFetchedBlock
    newOperation.queryCompletionBlock = qop.queryCompletionBlock
    self.publicDB.add(newOperation)
    }

    else if let error = error {
    print("Error:", error)
    }
    // No error and no cursor means the operation was successful
    else {
    print("Finished with records:", self.positionArray)
    if(!all){
    // my elaboration
    }
    else{
    // my elaboration
    }
    }
    })
    }

    self.publicDB.add(qop)


    With the first approach I can fetch at most 100 records.
    With the second approach I can fetch at most 400 records.
    But i need to fill my array with the all over 2000 records, how can achieve the result?










    share|improve this question

























      0












      0








      0








      Hi i'm trying to fetch all records from my publicDB in cloudkit, and currently there are more of 2000 records. How can I fetch them all and put them in an array?
      I've tryed these two methods without success. Can you please help me?



      1 Approach



          let predicate = NSPredicate(value: true)
      let query = CKQuery(recordType: "Position", predicate: predicate)
      query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

      publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in

      if error != nil {

      DispatchQueue.main.async(execute: { () -> Void in
      self.delegate?.errorUpdating(error: error! as NSError)
      return
      })
      } else {
      self.positionArray.removeAll(keepingCapacity: true)

      for record in results! {

      let position = Position(record: record as CKRecord, database: self.publicDB)
      self.positionArray.append(position)

      }
      }

      DispatchQueue.main.async(execute: { () -> Void in
      /* my elaboration with the complete result */
      })



      }


      2 Approach



          let predicate = NSPredicate(value: true)   
      let query = CKQuery(recordType: "Position", predicate: predicate)

      query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

      let qop = CKQueryOperation(query: query)

      qop.resultsLimit = 3000
      qop.recordFetchedBlock = { (record: CKRecord) in
      let position = Position(record: record, database: self.publicDB)
      self.positionArray.append(position)
      print(self.positionArray.count)
      }

      qop.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) in
      DispatchQueue.main.async(execute: { () -> Void in
      if let cursor = cursor {

      print("entro")
      let newOperation = CKQueryOperation(cursor: cursor)

      newOperation.recordFetchedBlock = qop.recordFetchedBlock
      newOperation.queryCompletionBlock = qop.queryCompletionBlock
      self.publicDB.add(newOperation)
      }

      else if let error = error {
      print("Error:", error)
      }
      // No error and no cursor means the operation was successful
      else {
      print("Finished with records:", self.positionArray)
      if(!all){
      // my elaboration
      }
      else{
      // my elaboration
      }
      }
      })
      }

      self.publicDB.add(qop)


      With the first approach I can fetch at most 100 records.
      With the second approach I can fetch at most 400 records.
      But i need to fill my array with the all over 2000 records, how can achieve the result?










      share|improve this question














      Hi i'm trying to fetch all records from my publicDB in cloudkit, and currently there are more of 2000 records. How can I fetch them all and put them in an array?
      I've tryed these two methods without success. Can you please help me?



      1 Approach



          let predicate = NSPredicate(value: true)
      let query = CKQuery(recordType: "Position", predicate: predicate)
      query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

      publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in

      if error != nil {

      DispatchQueue.main.async(execute: { () -> Void in
      self.delegate?.errorUpdating(error: error! as NSError)
      return
      })
      } else {
      self.positionArray.removeAll(keepingCapacity: true)

      for record in results! {

      let position = Position(record: record as CKRecord, database: self.publicDB)
      self.positionArray.append(position)

      }
      }

      DispatchQueue.main.async(execute: { () -> Void in
      /* my elaboration with the complete result */
      })



      }


      2 Approach



          let predicate = NSPredicate(value: true)   
      let query = CKQuery(recordType: "Position", predicate: predicate)

      query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

      let qop = CKQueryOperation(query: query)

      qop.resultsLimit = 3000
      qop.recordFetchedBlock = { (record: CKRecord) in
      let position = Position(record: record, database: self.publicDB)
      self.positionArray.append(position)
      print(self.positionArray.count)
      }

      qop.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) in
      DispatchQueue.main.async(execute: { () -> Void in
      if let cursor = cursor {

      print("entro")
      let newOperation = CKQueryOperation(cursor: cursor)

      newOperation.recordFetchedBlock = qop.recordFetchedBlock
      newOperation.queryCompletionBlock = qop.queryCompletionBlock
      self.publicDB.add(newOperation)
      }

      else if let error = error {
      print("Error:", error)
      }
      // No error and no cursor means the operation was successful
      else {
      print("Finished with records:", self.positionArray)
      if(!all){
      // my elaboration
      }
      else{
      // my elaboration
      }
      }
      })
      }

      self.publicDB.add(qop)


      With the first approach I can fetch at most 100 records.
      With the second approach I can fetch at most 400 records.
      But i need to fill my array with the all over 2000 records, how can achieve the result?







      ios iphone swift database cloudkit






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 12:15









      ultragranata15ultragranata15

      1




      1
























          1 Answer
          1






          active

          oldest

          votes


















          0














          There is indeed a limit of 400 records per fetch operation, so you need to check CKQueryCursor value returned by query completion block, and if it is not nil start another operation with it CKQueryOperation(cursor: cursor).



          So in principle your 2nd approach is correct. My guess is that your problem occurs due to threading issue, try removing DispatchQueue.main.async(execute: { () -> Void in.



          P.S. Check out how it is done in RxCloudKit (which handles big fetches automatically), it definitely works for fetching 1000+ records - RecordFetcher.queryCompletionBlock(cursor: CKQueryCursor?, error: Error?)






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458052%2fswift-get-all-records-from-cloudkit-public-database%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            There is indeed a limit of 400 records per fetch operation, so you need to check CKQueryCursor value returned by query completion block, and if it is not nil start another operation with it CKQueryOperation(cursor: cursor).



            So in principle your 2nd approach is correct. My guess is that your problem occurs due to threading issue, try removing DispatchQueue.main.async(execute: { () -> Void in.



            P.S. Check out how it is done in RxCloudKit (which handles big fetches automatically), it definitely works for fetching 1000+ records - RecordFetcher.queryCompletionBlock(cursor: CKQueryCursor?, error: Error?)






            share|improve this answer






























              0














              There is indeed a limit of 400 records per fetch operation, so you need to check CKQueryCursor value returned by query completion block, and if it is not nil start another operation with it CKQueryOperation(cursor: cursor).



              So in principle your 2nd approach is correct. My guess is that your problem occurs due to threading issue, try removing DispatchQueue.main.async(execute: { () -> Void in.



              P.S. Check out how it is done in RxCloudKit (which handles big fetches automatically), it definitely works for fetching 1000+ records - RecordFetcher.queryCompletionBlock(cursor: CKQueryCursor?, error: Error?)






              share|improve this answer




























                0












                0








                0







                There is indeed a limit of 400 records per fetch operation, so you need to check CKQueryCursor value returned by query completion block, and if it is not nil start another operation with it CKQueryOperation(cursor: cursor).



                So in principle your 2nd approach is correct. My guess is that your problem occurs due to threading issue, try removing DispatchQueue.main.async(execute: { () -> Void in.



                P.S. Check out how it is done in RxCloudKit (which handles big fetches automatically), it definitely works for fetching 1000+ records - RecordFetcher.queryCompletionBlock(cursor: CKQueryCursor?, error: Error?)






                share|improve this answer















                There is indeed a limit of 400 records per fetch operation, so you need to check CKQueryCursor value returned by query completion block, and if it is not nil start another operation with it CKQueryOperation(cursor: cursor).



                So in principle your 2nd approach is correct. My guess is that your problem occurs due to threading issue, try removing DispatchQueue.main.async(execute: { () -> Void in.



                P.S. Check out how it is done in RxCloudKit (which handles big fetches automatically), it definitely works for fetching 1000+ records - RecordFetcher.queryCompletionBlock(cursor: CKQueryCursor?, error: Error?)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 24 '18 at 17:36

























                answered Nov 24 '18 at 17:29









                Maxim VolginMaxim Volgin

                1,8421120




                1,8421120






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458052%2fswift-get-all-records-from-cloudkit-public-database%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Futebolista

                    Lallio

                    Jornalista