2
我的應用使用CloudKit備份領域數據並在用戶按某個按鈕時獲取數據。 我使用下面的代碼將文件夾中的「default.realm」文件上傳到iCloud。 而數據似乎上傳得很好。如何使用從iCloud下載的另一個領域替換默認領域
// create file path from app's documents folder
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"default.realm";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:kRecordName];
CKRecord *record = [[CKRecord alloc] initWithRecordType:kRecordType recordID:recordID];
if ([[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
CKAsset *asset = [[CKAsset alloc] initWithFileURL:[NSURL fileURLWithPath:fileAtPath]];
[record setObject:asset forKey:@"Realm"];
}
// upload
CKDatabase *privateDatabase = [[CKContainer defaultContainer] privateCloudDatabase];
[privateDatabase saveRecord:record completionHandler:^(CKRecord *record, NSError *error) {
// completion handling
}
下面是下載部分。我也可以下載,但似乎領域文件沒有被替換。
CKDatabase *privateDatabase = [[CKContainer defaultContainer] privateCloudDatabase];
CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:kRecordName];
// fetch realm from cloud
[privateDatabase fetchRecordWithID:recordID completionHandler:^(CKRecord *record, NSError *error) {
if (!error) {
CKAsset *realmAsset = record[@"Realm"];
NSData *realmData = [NSData dataWithContentsOfURL:realmAsset.fileURL];
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"default.realm";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// delete existing default.realm file in documents
if ([[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] removeItemAtPath:fileAtPath error:&error];
}
// create a new default.realm file with downloaded data
if([[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:realmData attributes:nil]) {
// code goes thru here but nothing changes
}
}
}];
我想替換整個領域文件。我究竟做錯了什麼?我應該從哪裏開始? 任何意見將不勝感激。
遵循您的指導,我可以在不更改名稱的情況下交換領域文件。似乎沒有強有力的參考。非常感謝你,你救了我的一天! –