将更改部署到生产环境时,如何为 CKRecord 中的字段添加默认值?

How do I add a default value for field in CKRecord when deploy changes to production?

问题如下:

目前我在开发模式的云仪表盘中有一个Service记录类型:

但是第一个版本是 WITHOUT createdAt 字段。

我确实将第一个版本部署到生产模式,这很好。然后我通过添加 createdAt 字段来更改 Service。我确实将它部署到生产环境中。所以在生产中我有这样的字段:

没有 createdAt 日期。

在我开发应用程序并尝试获取所有 Service 记录时......一切都很好。它们被获取并在应用程序中工作。所以我将更改部署到生产模式,将应用程序提交到应用程序商店。 Apple 确实对其进行了审查......并且......它无法正常工作。 为什么?

它们没有默认 createdAt 值...当我获取所有这些值时...没有获取任何内容(因为应用程序中没有显示任何内容)。

但是...

当我在 生产模式 中手动更新 createdAt 时,如您所见:

然后来自 AppStore 的应用程序运行正常,这些记录被提取并显示在应用程序中。

它们没有出现在应用程序中可能是什么原因? 我能以某种方式为当前在云中的用户设置默认值吗?

我有 638 条记录要更新:(

既然你告诉我你必须使用自定义 createdAt 日期,而不是 CKRecord 的自然 creationDate 属性,你应该可以做到像这样:

func getServiceRecords() {
    let predicate:NSPredicate = NSPredicate(value: true)
    let query:CKQuery = CKQuery(recordType: "Service", predicate: predicate)

    // Create an empty array of CKRecords to append ones without createdAt value
    var empty:[CKRecord] = []

    // Perform the query
    if let database = self.publicDatabase {

        database.perform(query, inZoneWith: nil, completionHandler: { (records:[CKRecord]?, error:Error?) -> Void in

            // Check if there is an error
            if error != nil {

            }
            else if let records = records {

                for record in records {
                    if let _ = record.object(forKey: "createdAt") as! Date? {
                        // This record already has assigned creationDate and shouldnt need changing
                    } else {
                        // This record doesn't have a value create generic one and append it to empty array
                        record.setObject(Date() as CKRecordValue?, forKey: "createdAt")
                        empty.append(record)
                    }
                }

                self.saveCustomCreationDates(records: empty)
            }

        })

    }
}

func saveCustomCreationDates(records: [CKRecord]) {
    if let database = self.publicDatabase {

        // Create a CKModifyRecordsOperation
        let operation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: nil)
        operation.savePolicy = .allKeys
        operation.qualityOfService = .userInteractive
        operation.allowsCellularAccess = true
        operation.modifyRecordsCompletionBlock = { (records:[CKRecord]?, deleted:[CKRecordID]?, error:Error?) in
            if error != nil {
               // Handle error
            }
            else if let records = records {

                for record in records {

                    if let creationDate = record.object(forKey: "createdAt") as! Date? {
                        // You can verify it saved if you want
                        print(creationDate)
                    }
                }

            }

        }
        // Add the operation
        database.add(operation)
    }

}