How to get Sqlite database file when application is running on device?

前端 未结 8 1598
迷失自我
迷失自我 2020-12-15 01:08

I am facing problem in accessing database file when I am running it on device. How can I get that file? There is no problem in accessing file when I am running application o

相关标签:
8条回答
  • 2020-12-15 01:56

    Most likely your database is in the apps Documents directory. So you would need to call that directory by using:

    - (NSString *)applicationDocumentsDirectory {
        return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    }
    
    0 讨论(0)
  • 2020-12-15 01:56

    @nitish :

    I have a code that will access the sqlite database file when application is running on device.

    - (void) initDatabase
    {
    
        BOOL success;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error;
        NSArray *paths =    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                            NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *writableDBPath = [documentsDirectory
                                stringByAppendingPathComponent:@"contacts.db"];
    
        success = [fileManager fileExistsAtPath:writableDBPath];
    
        dbpath = [writableDBPath UTF8String];
    
        NSLog(@"path : %@", writableDBPath);
    
        if (success) return;
        // The writable database does not exist, so copy the default to the appropriate
        //  location.
    
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
                               stringByAppendingPathComponent:@"contacts.db"];
    
        success = [fileManager fileExistsAtPath:defaultDBPath];
        //if(success) return;
    
    
        success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        if (!success)
        {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.",[error localizedDescription]);
        }
    
        dbpath = [writableDBPath UTF8String];
        NSLog(@"path : %@", writableDBPath);
    }
    

    "NSLog()" will give you path for sqlite database file. It works for both simulator & device. Hope it will work for you.

    0 讨论(0)
提交回复
热议问题