替换 CloudKit 记录时遇到问题
Posted
技术标签:
【中文标题】替换 CloudKit 记录时遇到问题【英文标题】:Trouble Replacing CloudKit Records 【发布时间】:2016-10-27 01:00:55 【问题描述】:我在“if (NSKeyedUnarchiver.unarchiveObject(with: loadedData as! Data) as? CKRecord) != nil
”行收到致命错误:“无法将 'NSTaggedPointerString' 类型的值转换为 'NSData'”。
当我尝试将 locationRecord 保存为默认值时,还有另一个致命错误:“尝试将非属性列表对象设置为关键 locationData 的 NSUserDefaults/CFPreferences 值”。
var locationRecord = CKRecord(recordType: "location")
func getRecordToUpdate(_ locations:CLLocation)
if defaults1.object(forKey: "locationData") == nil
locationRecord.setObject(locations, forKey: "location")
defaults1.set(locationRecord, forKey: "locationData")
self.updateLocationRecord(locations: locations)
else
if let loadedData = defaults1.object(forKey: "locationData")
print("continue")
if (NSKeyedUnarchiver.unarchiveObject(with: loadedData as! Data)) != nil
let publicDB = CKContainer.default().publicCloudDatabase
publicDB.fetch(withRecordID: locationRecord.recordID,completionHandler:
(record, error) in
if error == nil
publicDB.delete(withRecordID: (record?.recordID)!, completionHandler:
(record, error) in
if(error == nil)
print("old record delete")
self.locationRecord.setObject(locations, forKey: "location")
self.defaults1.set(self.locationRecord, forKey: "locationData")
self.updateLocationRecord(locations: locations)
else
)
else
print("Error fetching previous record")
)
func updateLocationRecord(locations: CLLocation)
locationRecord.setObject(locations, forKey: "location")
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(locationRecord, completionHandler: record, error in
)
if error == nil
print("Location saved")
【问题讨论】:
您必须查询现有记录并更新它。您每次都在创建一个新的CKRecord
。
我如何确定正在获取的是用户记录? @rmaddy
您的location
记录类型需要适当的字段。现在看起来你只有一个 location
字段。因此,您所拥有的只是一堆“位置”记录,其中只有一个 CLLocation
字段。您无法知道给定记录的用途。
您能否提供一个示例,说明如何使用正确的参数初始化记录。 @rmaddy
这取决于您和您的需求。
【参考方案1】:
这是最终为我工作的代码:
if let loadedData = defaults1.object(forKey: "locationData") as? Data
let litt = NSKeyedUnarchiver.unarchiveObject(with: loadedData) as! CKRecord
let publicDB = CKContainer.default().publicCloudDatabase
publicDB.fetch(withRecordID: litt.recordID ,completionHandler:
(record, error) in
if error == nil
publicDB.delete(withRecordID: (record?.recordID)!, completionHandler:
(record, error) in
if(error == nil)
print("old record delete")
let id = self.locationRecord.recordID.recordName
self.locationRecord.setObject(locations, forKey: "location")
self.defaults1.set(id, forKey: "locationData")
self.updateLocationRecord(locations: locations)
else
)
else
print("Error fetching previous record")
)
【讨论】:
以上是关于替换 CloudKit 记录时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章