iossqlitensdatacaf

NSData to *.caf file


I'm trying to save an audio file in my SQLite DB and restore it.

I stored this way to NSData:

NSData *audioData = [NSData dataWithContentsOfFile:[audios objectAtIndex:A]];
insert_stmt = "INSERT INTO audios (fecha, audio) VALUES (?, ?)";

if( sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK )
{
    sqlite3_bind_text(statement, 1, [Fecha UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_blob(statement, 2, [audioData bytes], [audioData length], SQLITE_TRANSIENT);
    sqlite3_step(statement);
}
else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(contactDB) );
sqlite3_finalize(statement);

And I get it back in this way:

while (sqlite3_step(SQLstatement) == SQLITE_ROW)
{
    int length = sqlite3_column_bytes(SQLstatement, 2);
    NSData* data = nil;
    data       = [NSData dataWithBytes:sqlite3_column_blob(SQLstatement, 2) length:length];

    NSArray *dirPaths;
    NSString *docsDir;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];

    NSString *ruta = [NSString stringWithFormat:@"%@-%d-sound.caf", fecha, contador];
    NSString *soundFilePath = [docsDir stringByAppendingPathComponent:ruta];

    [[NSFileManager defaultManager] createFileAtPath:soundFilePath contents:data attributes:nil];
}

But when I create the audio file that only contains 0 Kb


Solution

  • As stated, you are using the wrong column index. In your query to load the data you use:

    SELECT fecha, audio FROM audios WHERE fecha = XXX;
    

    This means you need to use column index 1, not 2 to access the audio column.

    This is the worst part of the sqlite3 C-API. The sqlite3_bind_xxx functions use a 1-based column index while the sqlite3_column_xxx functions use a 0-based column index.