2014-09-13 34 views
0

我在iOS應用程序中使用一個名爲testSqlite.sqlite的sqlite數據庫。我想將它複製到應用程序文件夾。但該文件不會複製到所需的位置。我也添加了我的源代碼。請幫助如何在運行時將數據庫從主包複製到應用程序文件夾?

NSString *docsDir; 
NSArray *dirPaths; 
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
docsDir = dirPaths [0]; 

NSString *backupPath = [[NSBundle mainBundle] pathForResource:@"testSqlite" ofType:@"sqlite"]; 
NSLog(@"backup is %@ ",backupPath); 
if (![[NSFileManager defaultManager] fileExistsAtPath: docsDir]) { 
    if (backupPath) { 
     BOOL copiedBackup = [[NSFileManager defaultManager] copyItemAtPath:backupPath toPath:docsDir error:nil]; 
     if (!copiedBackup) { 
      // copying backup db failed, bail 
      NSLog(@"Copying backup db failed"); 
     } 
     else 
      NSLog(@"\n\ndatabase created"); 
    } 
} 
+0

請分享NSLog輸出 – freshking 2014-09-13 12:32:27

回答

1

Apple建議使用URL's和下面的代碼在我的應用程序:

NSString *docDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *filePath = [docDirectory stringByAppendingPathComponent:@"testSqlite.sqlite"]; 

NSURL *fileDocURL = [NSURL fileURLWithPath:[docDirectory stringByAppendingPathComponent:@"ProductInventory.plist"]]; 
NSURL *newFileURL = [NSURL fileURLWithPath:filePath]; 
NSLog(@"fileDocURL: %@, newFileURL: %@", fileDocURL, newFileURL); 

NSError __autoreleasing *error; 
BOOL success = [[NSFileManager defaultManager] copyItemAtURL:fileDocURL toURL:newFileURL error:&error]; 
if (success) { 
     NSLog(@"Transaction file was copied"); 
     // Delete the old file 
     [[NSFileManager defaultManager] removeItemAtURL:fileDocURL error:nil]; 
} else { 
     NSLog(@"NO transaction file to copy, Error: %@", [error localizedDescription]); 
} 
+0

這是nsurl。但我需要它複製到目錄文件folder.thanks的評論@Hannes Sverrisson – Asaduzzaman 2014-09-13 12:27:48

+0

@ user3903633您使用URLs在文件夾之間複製文件。試試看,代碼! – 2014-09-13 12:30:38

+0

@ user3903633您應該在此接受您的問題的答案,否則人們可能會停止回答。 – 2014-09-13 16:41:06

0

嘗試拷貝主束這個代碼文檔目錄文件夾運行。

NSString *pathsToReources = [[NSBundle mainBundle] resourcePath]; 
    NSString *yourOriginalDatabasePath = [pathsToReources stringByAppendingPathComponent:@"lunchDB.sqlite"]; 

    NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [pathsToDocuments objectAtIndex: 0]; 

     NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"lunchDB.sqlite"]; 

     if (![[NSFileManager defaultManager] isReadableFileAtPath: dbPath]) { 

    if ([[NSFileManager defaultManager] copyItemAtPath: yourOriginalDatabasePath toPath: dbPath error: NULL] != YES) 

    NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, dbPath); 

    } 

在這裏替換您的文件名「lunchDB.sqlite」。 謝謝。

+0

感謝所有的評論。我使用這些解決方案並解決我的問題。再次請求評論 – Asaduzzaman 2014-09-15 11:38:59

+0

請接受並向上.. – ilesh 2014-09-15 12:06:44

相關問題