NestedCloudkitCodable
提供一个简单的方式,将自定义对象编码和解码到/从 Cloudkit,通过自定义 Encoder
和 Decoder
将您的结构转换为 CKRecord
并反向转换。它可以用于嵌套对象。
受到 CloudkitCodable 的启发。
安装
CocoaPods
将以下条目添加到您的 Podfile
pod 'NestedCloudKitCodable'
然后运行 pod install
。
Carthage
将以下条目添加到您的 Cartfile
github "ggirotto/NestedCloudkitCodable"
然后运行 carthage update
。
如果您第一次在该项目中使用 Carthage,请参阅 Carthage 文档 获取额外的安装步骤。
手动安装
- 将“资源”文件夹拖放到您的项目中的任何位置。
用法
CKCodable
协议
在您要转换为/从 CKRecord
的模型中实现 CustomCloudkitCodable
。该协议需要实现两个属性。
var cloudKitRecordType: String { get }
是表示该对象在 CloudKit
容器中记录类型的 Record Type
。
var cloudKitIdentifier: String { get }
是该对象的标识符,将在将对象转换为 CKRecord
时用作标识符。
重要:请使用唯一标识符为您的对象以避免创建不必要的 CKRecords
。
此协议还允许您实现以下功能
func ignoredProperties() -> [String]
正如其名称所暗示的,使您能够忽略某些属性在结果 CKRecord
中的编码。
CLLocation
CLLocation
属性具有特殊的行为。由于它们是 CloudKit
的原始数据类型,但不是 Codable
协议的,因此需要创建一个解决方案来编码/解码它们。
单个 CLLocation
必须以 "latitude;longitude"
格式编码,即使用分号(;)分隔的字符串。多个 CLLocations
必须遵循相同的模式,并且必须作为使用上述相同模式的字符串数组进行编码/解码。
示例
编码
令 School
为您的自定义对象,如下所示。
struct School: CKCodable {
var cloudKitRecordType: String {
return "School"
}
var cloudKitIdentifier: String {
return id
}
var id = UUID().uuidString
var name: String!
var location: CLLocation!
var students: [Person]!
var director: Person!
var books: [Book]!
}
要对其进行编码,只需使用 CKRecordEncoder
对其进行编码,简单如下。
let school = School()
do {
let encodedRecords = try CKRecordEncoder().encode(school)
...
// Save encodedRecords to your Cloudkit database
} catch let error as CKCodableError {
// Handle errors
} catch { }
解码
考虑相同的 School
对象,要将其从原始的 CKRecord
解码回 School
对象,如下使用 CKRecordDecoder
。
let schoolRecord = ... // Your school object CKRecord fetched from CloudKit
let referenceDatabase = CKContainer.default().publicCloudDatabase // Database where related CKRecords are stored
CKRecordDecoder().decode(School.self,
from: schoolRecord,
referenceDatabase: referenceDatabase) { (decodedSchool, error) in
if let error = error {
// Adds your error handling here
}
let schoolObject = decodedSchool as! School
...
}
请注意,decode
函数是异步的。这是必要的,因为当您的对象与嵌套对象相关联时,解码函数在解码原始对象之前会从这些嵌套对象中检索所有 CKRecords
。在上面的示例中,decode
函数将检索来自 students
、books
和 director
嵌套对象的所有记录,然后解码主要的 School
对象。
还需要发送这些记录将要查找的 referenceDatabase
。
您可以在这里找到此示例对象。
反馈/贡献
感谢使用这个库!如果您在使用过程中遇到一些麻烦或发现某些不一致或错误,请创建一个问题,以便我进行调查。
也可以自由地为项目做出贡献,创建一个 PR :)