Search code examples
swiftsortingnsdatecloudkitckrecord

How can I show the post closest to today's date from CloudKit?


I am developing a social media app for fun with CloudKit and I've been stuck on the issue of displaying the most recently posted images first.

I have a record type setup on CloudKit to have the picture and a date posted, which is programmatically set to the date of the iPhone posting.

Here is my code for displaying the images when you open the app:

override func viewDidAppear(animated: Bool) {
    let container = CKContainer.defaultContainer()
    let publicDatabase = container.publicCloudDatabase
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Post", predicate: predicate)

    publicDatabase.performQuery(query, inZoneWithID: nil) { results, error in
        if error == nil { // There is no error
            results
            print("No Error")
            if results!.count > 0 {
                print("Found some")
                self.newResults = results!
                let randomNumber = arc4random_uniform(UInt32(results!.count - 1)) + 0
                let randomNumberInt = Int(randomNumber)
                let record = results![randomNumberInt]
                let img = record.valueForKey("Picture") as? CKAsset
                let image = UIImage(contentsOfFile: img!.fileURL.path!)
                self.imageView.image = image
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                })
            }
        }
        else {
            print(error)
        }
    }
}

For now, this code just displays a random image in the results array. But I want to somehow sort the results and display the most recently posted image using the DatePosted CloudKit record type property. I am at a complete loss on how to do this, so any help would be very much appeciated!


Solution

  • This code shows you the basics. It doesn't get the latest, it gets the oldest, but you can I am sure figure it out:) Makes use of an excellent and very interesting piece of swift for the dates that you can read about here.

    http://www.globalnerdy.com/2015/02/02/how-to-work-with-dates-and-times-in-swift-part-three-making-date-arithmetic-more-swift-like/

     func cleanup4Cloud() {
        let container = CKContainer(identifier: "iCloud.ch")
        let publicDB = container.publicCloudDatabase
       let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: "Blah", predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    
        cleanUpOperation = CKQueryOperation(query: query)
        cleanUpOperation.desiredKeys = ["record.recordID.recordName"];
    
        cleanUpOperation.recordFetchedBlock = { (record) in
            self.recordsRead.append(record.recordID)
            let recordDOC = record["creationDate"] as! NSDate
    
            let newTimeInterval = 4.hours.fromNow
    
            let formatter = NSDateFormatter()
            formatter.dateStyle = .NoStyle
            formatter.timeStyle = .MediumStyle
    
            let string = formatter.stringFromDate(newTimeInterval)
            let string2 = formatter.stringFromDate(recordDOC)
    
            if newTimeInterval.timeIntervalSinceReferenceDate >  recordDOC.timeIntervalSinceReferenceDate {
             print("recordDOC is older than \(string2) [\(string)]")
            }
        }
        cleanUpOperation.queryCompletionBlock = {(cursor, error) in
            if error != nil {
                print("ting, busted",error!.localizedDescription)
            } else {
               print("self.recordsRead.count \(self.recordsRead.count)")
                self.cleanOutDB()
            }
    
        }
        cleanUpOperation.qualityOfService = .Background
    
        publicDB.addOperation(cleanUpOperation)
    }