我正在使用CloudKit开发社交媒体应用程序以获得乐趣,而且我一直坚持首先显示最近发布的图像的问题。
我在CloudKit上有一个记录类型设置,用于显示图片和日期,这是以编程方式设置为iPhone发布日期。
以下是我打开应用时显示图片的代码:
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)
}
}
}
目前,此代码只在results
数组中显示随机图像。但我想以某种方式对结果进行排序,并使用DatePosted
CloudKit记录类型属性显示最近发布的图像。我完全不知道如何做到这一点,所以任何帮助都会非常明确!
答案 0 :(得分:1)
此代码向您展示了基础知识。它没有获得最新版本,它获得了最新版本,但你可以确定它是明白的:)在你可以阅读的日期中使用一个优秀且非常有趣的swift。
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)
}