2014-02-08 2 views
0

코어 데이터 UIManagedDocument에 대한 백업을 생성하여 iCloud에 저장하려고합니다. 이 일을 시도하는 메신저 이후 2 개월 이상> 나는 그 일을하는 방법을 이해하지 못합니다. 이 모든 ... 메신저 적어도 지역의 백업을 만들려고 인터넷에는 정보가없고 그것은 작동 나던 중 하나 이 코드입니다 :UImanagedDocument의 persistentStore iCloud 백업

-(void)testCopyStoreToDocuments 
{ 
    AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; 
    [appDelegate.userDataDocument closeWithCompletionHandler:^(BOOL closed) 
    { 
     if(closed) 
     { 
      @autoreleasepool { 
       NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; 
       NSString *sourceFile = [[[[LoadingManager localDocumentURL]URLByAppendingPathComponent:@"StoreContent"]path] stringByAppendingPathComponent:@"persistentStore"]; 
       NSURL *sourceURL = [NSURL fileURLWithPath:sourceFile]; 

       [fc coordinateReadingItemAtURL:sourceURL options:NSFileCoordinatorReadingWithoutChanges error:nil byAccessor:^(NSURL *sourceURLtoUse) { 
        NSError *error = nil; 
        NSFileManager *fm = [[NSFileManager alloc] init]; 
        NSString *destinationFile = [[[LoadingManager localDocumentsDirectoryURL]path] stringByAppendingPathComponent:@"persistentStore"]; 


        //simply copy the file over 
        BOOL copySuccess = [fm copyItemAtPath:[sourceURLtoUse path] 
                toPath:destinationFile 
                error:&error]; 
        if (copySuccess) { 
         NSLog(@" copied file successfully"); 
        } else { 
         NSLog(@"Error copying item at path: %@\nTo path: %@\nError: %@", sourceFile, destinationFile, error); 
        } 
       }]; 
       fc = nil; 
      } 

     } 
    }]; 
} 
-(void)testReplaceStore 
{ 
    AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; 
    [appDelegate.userDataDocument closeWithCompletionHandler:^(BOOL closed) 
    { 
     if(closed) 
     { 
      NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; 
      [fc coordinateWritingItemAtURL:[[[LoadingManager localDocumentURL]URLByAppendingPathComponent:@"StoreContent"]URLByAppendingPathComponent:@"persistentStore"] options:NSFileCoordinatorWritingForDeleting error:nil byAccessor:^(NSURL *sourceURLtoUse){ 
       NSLog(@"%@",sourceURLtoUse); 
       NSError * error = nil; 
       NSLog(@"replacment: %hhd",[[NSFileManager defaultManager]replaceItemAtURL:sourceURLtoUse withItemAtURL:[[LoadingManager localDocumentsDirectoryURL]URLByAppendingPathComponent:@"persistentStore"] backupItemName:@"backUp" options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:nil error:&error]); 
       NSLog(@"%@",error); 
      }]; 
      NSLog(@"stores: %@",appDelegate.userDataDocument.managedObjectContext.persistentStoreCoordinator.persistentStores); 
      [appDelegate.userDataDocument saveToURL:appDelegate.userDataDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL saved) 
       { 
        if(saved) 
        { 
         [appDelegate.userDataDocument openWithCompletionHandler:^(BOOL opened) 
         { 
          if(opened) 
          { 
           NSLog(@"opened"); 
          } 

         }]; 
        } 
        else 
        { 
         NSLog(@"failed to save"); 
         NSLog(@"stores: %@",appDelegate.userDataDocument.managedObjectContext.persistentStoreCoordinator.persistentStores); 
        } 
       }]; 
     } 
    }]; 
} 

그것은 교체를 호출 할 때 오류가 Nslogs :

replacment: 0 
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x15d91540 {NSFileNewItemLocationKey=file:///var/mobile/Applications/85974C93-75FD-406A-B1BF-EDE7DFC25FE2/Documents/persistentStore, NSFileOriginalItemLocationKey=file:///var/mobile/Applications/85974C93-75FD-406A-B1BF-EDE7DFC25FE2/Documents/Data%20Document/StoreContent/persistentStore, NSUnderlyingError=0x15db0080 "The operation couldn’t be completed. (Cocoa error 260.)", 
+0

위의 코드에서 어떤 문제가 발생했는지 설명해 주시면 도움이됩니다. –

+0

@TomHarrington ive 님이 질문을 업데이트했습니다. – t0a0

+0

파일이 이미 있습니까? 대상 파일에 이미 파일이 있는지 확인하고 복사본 전에 삭제하십시오! –

답변

0

방금이 코드를 테스트 한 결과 정상적으로 작동합니다. 다음은 샘플 응용 프로그램입니다. http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/

대상 파일이 이미 있으면 오류가 발생합니다.

/** Copies file to iCloud container removing the target file if it already exists 

@param docURL URL of UIManagedDocument whose store file is to be copied (its Core Data Store must not be shared in iCloud! 
*/ 
- (void)copyFileToICloud:(NSURL*)docURL { 
    @autoreleasepool { 
     NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; 
     NSURL *sourceURL = [[docURL URLByAppendingPathComponent:@"StoreContent"] URLByAppendingPathComponent:@"persistentStore"]; 

     // Local directory - test 
     //NSString *destinationFile = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"persistentStore_backup"]; 

     NSURL *destinationURL = [[[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:@"persistentStore_backup"]; 


     FLOG(@" source file is %@", sourceURL); 
     FLOG(@" target file is %@", destinationURL); 

     NSError *cError; 

     [fc coordinateWritingItemAtURL:destinationURL options:NSFileCoordinatorWritingForReplacing error:&cError byAccessor:^(NSURL *newURL) { 
      NSError *error = nil; 
      NSFileManager *fm = [[NSFileManager alloc] init]; 

      // Delete it if it already exists 
      if ([fm fileExistsAtPath:[newURL path]]) { 
       FLOG(@" target file exists"); 
       if (![fm removeItemAtURL:newURL error:&error]) { 
        FLOG(@" error unable to remove target file"); 
        NSLog(@"Error removing item Error: %@, %@", error, error.userInfo); 
        return; 
       } else { 
        FLOG(@" target file removed"); 
       } 
      } 

      //simply copy the file over 
      BOOL copySuccess = [fm copyItemAtPath:[sourceURL path] 
              toPath:[newURL path] 
              error:&error]; 
      if (copySuccess) { 
       NSLog(@" copied file successfully"); 
      } else { 
       NSLog(@"Error copying items Error: %@, %@", error, error.userInfo); 
      } 
     }]; 

     if (cError) { 
      FLOG(@" error is %@", cError); 
     } 

     fc = nil; 
    } 
} 

편집 : 몇 가지 추가 기억해야 할 :

  • 당신이 WAL 모드를 사용하는 경우 (또는 iOS7에 대한 기본 코어 데이터 모드, OS를 X 10.9) 다음은 복사해야합니다 ~ wal 및 ~ shm 파일도 저장하십시오. 전체 StoreContent 디렉토리를 더 잘 복사하십시오.

  • 파일을 iCloud에서 복사하려면 메타 데이터 쿼리를 통해 파일을 찾은 다음 다운로드 상태를 확인해야합니다. 다운로드를 실행하고 다운로드하기 전에 다운로드 한 파일을 확인해야합니다 .

관련 문제