我是CloudKit的新手,我无法将数据库中的资源连接到我的应用中的ImageView和TextView。在我的CloudKit数据库中,在记录类型下,我创建了一个名为" Companies"的记录。然后我转到Public Data-> Default Zone,然后创建了一个名为" myCompany"的记录的新实例。在" myCompany"我有两个资产,一个图像和一个.txt文件。我想将这些资产连接到我的应用程序。我不确定我是否需要使用CKQuery或什么是最好的方法。任何建议将不胜感激。以下是我到目前为止的情况。如果有更好的方式,请随时提供反馈,我很乐意知道。谢谢。
import UIKit
import CloudKit
class LearnViewController: UIViewController {
@IBOutlet weak var theImage: UIImageView!
@IBOutlet weak var theText: UITextView!
let myRecord = CKRecord(recordType: "Companies" )
var image: UIImage!
let database = CKContainer.defaultContainer().publicCloudDatabase
func loadCoverPhoto(completion:(photo: UIImage!) -> ()) {
dispatch_async(
dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)){
var image: UIImage!
let coverPhoto = self.myRecord.objectForKey("Picture") as CKAsset!
if let asset = coverPhoto {
if let url = asset.fileURL {
let imageData = NSData(contentsOfFile: url.path!)!
image = UIImage(data: imageData)
}
}
completion(photo: image)
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadCoverPhoto() { photo in
dispatch_async(dispatch_get_main_queue()) {
self.theImage.image = photo
}
}
答案 0 :(得分:3)
如果您通过执行类似以下的获取来了解recordId,则可以直接获取记录:
database.fetchRecordWithID(CKRecordID(recordName: recordId), completionHandler: {record, error in
或者,如果您不知道ID,则应使用以下代码查询记录。只需创建正确的NSPredicate。查询可以返回多于1条记录。
var query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true))
var operation = CKQueryOperation(query: query)
operation.recordFetchedBlock = { record in
// is this your record...
}
operation.queryCompletionBlock = { cursor, error in
self.handleCallback(error, errorHandler: {errorHandler(error: error)}, completionHandler: {
// ready fetching records
})
}
operation.resultsLimit = CKQueryOperationMaximumResults;
database.addOperation(operation)
在使用fetchRecordWithID选项的情况下,代码如下所示:
override func viewDidLoad() {
super.viewDidLoad()
database.fetchRecordWithID(CKRecordID(recordName: recordId), completionHandler: {record, error in
self.myRecord = record
loadCoverPhoto() { photo in
dispatch_async(dispatch_get_main_queue()) {
self.theImage.image = photo
}
}
}
}