从Cloudkit中快速删除CKRecord
问题描述:
我想通过此功能更新用户的位置。最初它每次都保存用户的位置,但我添加了将在评论下方的代码。我怎样才能确保被删除的记录是旧的位置?从Cloudkit中快速删除CKRecord
let locationRecord = CKRecord(recordType: "location")
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()//
locationRecord.setObject(location, forKey: "location")
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveRecord(locationRecord) { record, error in
}
if error == nil
{
print("Location saved")
self.loc1 = location!
}
//testing code below
let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: [locationRecord.recordID])
operation.savePolicy = .AllKeys
operation.modifyRecordsCompletionBlock = { added, deleted, error in
if error != nil {
print(error)
} else {
print("location updated")
}
}
CKContainer.defaultContainer().publicCloudDatabase.addOperation(operation)
}
答
要做到这一点,最好的方法是更新现有的,正如@Michael指出的那样。简单的做法是在您第一次创建记录时,将recordID保存为默认值。例如,
func getRecordToUpdate(locations:[CLLocation])->CKRecord?{
let defaults = NSUserDefaults.standardUserDefaults()
var locationRecord:CKRecord
if defaults.objectForKey("locationRecordID") == nil{
//Create a new record and save its id
locationRecord = CKRecord(recordType: "location")
defaults.setObject(locationRecord.recordID, forKey: "locationRecordID")
self.updateLocationRecord(locationRecord, locations)
}else{
//Fetch the already existing record
let publicDB = CKContainer.defaultContainer().publicCloudDatabase
publicDB.fetchRecordWithID((defaults.objectForKey("locationRecordID") as! CKRecordID), completionHandler{
(record, error) in
if error == nil{
self.updateLocationRecord(record, locations)
}else{
print("Error fetching previous record")
}
}
}
}
创建一个新的功能,
func updateLocationRecord(locationRecord:CKRecord, locations:[CLLocation]){
//Put your code from "let location..." to just above the testing code
//You may want to fix the block syntax in the call to saveRecord
}
那么在原始的LocationManager方法,拿出一切,并把
self.getRecordsToUpdate(locations)
你为什么想添加一个新的CKRecord和删除旧的,而不是只保留一个并更新它? – Michael
我将如何修改现有的? @michael – Steve
通过保留对现有参考的本地引用 - 可能在NSUserDefaults中。如果它不存在,则需要首次保存,否则,您需要获取现有记录并进行更新,然后将其保存回去。查看doco中的“获取现有记录” - https://developer.apple.com/library/ios/documentation/CloudKit/Reference/CKRecord_class/ – Michael