I'm trying to open a file 'd.mp3' that I added to my Xcode 8.0 project.
If I double-click Xcode > project > 'd.mp3' the file plays just fine.
But, when Xcode runs my app on my iPhone6+ (iOS 10.0.1) then fopen() returns 0 for the file handle.
Code and output below...
bool read_next_chunk( char* relative_file_pathname, unsigned char* chunk_buffer, int chunk_size_bytes, FILE* file_handle )
{
const bool dbg = true;
// Get absolute file pathname:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *program_directory = [paths objectAtIndex:0];
NSString* absolute_pathname = [NSString stringWithFormat: #"%#/%s", program_directory, relative_file_pathname ];
if( dbg ) printf("\n%s: file '%s'. Path '%s'.", __FUNCTION__, relative_file_pathname, [absolute_pathname UTF8String] );
// Open file if not already open:
if( file_handle == NULL )
{
if( dbg ) printf("\n%s Open file %s.", __FUNCTION__, relative_file_pathname );
file_handle = fopen( [absolute_pathname UTF8String], "rb" ); // open for binary reading
if( dbg ) printf("\n%s file_handle %d.", __FUNCTION__, file_handle);
}
if( file_handle )
{
// Read next chunk of file into file_content_string:
int total_read_bytes = (int)fread( chunk_buffer, 1, chunk_size_bytes, file_handle );
if( total_read_bytes != chunk_size_bytes )
{
printf("\n %s: %d total_read_bytes != %d chunk_size_bytes -- FAULT!! <<<<<<<<<<<",__FUNCTION__, total_read_bytes, chunk_size_bytes);
return false;
}
return true;
}
else
{
printf("\ %s: Cannot open '%s' FAULT!! <<<<<<<<<<<", __FUNCTION__, relative_file_pathname );
return false;
}
}
read_next_chunk: file 'd.mp3'. Path '/var/mobile/Containers/Data/Application/C8B87C49-C6CF-4677-B775-6B3DF6EFD908/Documents/d.mp3'.
read_next_chunk Open file d.mp3.
read_next_chunk file_handle 0. read_next_chunk: Cannot open 'd.mp3' FAULT!! <<<<<<<<<<<
As rmaddy said, it is likely not in your documents directory. Try something like this:
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"d" ofType:#"mp3"];
Related
I have created a table(REPORTDATA) in existing database. I am trying to insert the values in to table. But it is not inserted. I am using the following code.
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [docsDir stringByAppendingPathComponent:#"Album.db"];
const char *dbpath = [databasePath UTF8String];
NSString *insertSQL;
if (sqlite3_open(dbpath, & albumDB) == SQLITE_OK)
{
int rowCount = [self GetArticlesCount];
rowCount += 1;
NSString *tempcount = [NSString stringWithFormat:#"%d", rowCount];
insertSQL = [NSString stringWithFormat: #"INSERT INTO REPORTDATA (Num, Json) VALUES ('%#','%#')", tempcount, tempcount];
char *errmsg=nil;
if(sqlite3_exec(albumDB, [insertSQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
{
}
else
{
NSLog(#"Error Message is =%s",errmsg);
}
}
sqlite3_close(albumDB);
Get number of rows in a table:
- (int) GetArticlesCount
{
int count = 0;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [docsDir stringByAppendingPathComponent:#"Album.db"];
if (sqlite3_open([self.databasePath UTF8String], &albumDB) == SQLITE_OK)
{
const char* sqlStatement = "SELECT COUNT(*) FROM REPORTDATA";
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(albumDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
//Loop through all the returned rows (should be just one)
while( sqlite3_step(statement) == SQLITE_ROW )
{
count = sqlite3_column_int(statement, 0);
}
}
else
{
NSLog( #"Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(albumDB) );
}
sqlite3_finalize(statement);
sqlite3_close(albumDB);
}
return count;
}
I am getting
Error Message is =(null).
I'd suggest examining the actual return value of sqlite3_exec:
int rc;
char *errmsg = NULL;
if ((rc = sqlite3_exec(albumDB, [insertSQL UTF8String], NULL, NULL, &errmsg)) == SQLITE_OK) {
NSLog(#"Insert succeeded");
} else {
NSLog(#"Insert failed: %s (%ld)", errmsg, (long)rc);
if (errmsg) sqlite3_free(errmsg);
}
You report that it returned 21, which is SQLITE_MISUSE. This is typical if you called the API functions in the wrong order (e.g. performing some SQL after the database was closed).
The GetArticlesCount method is reopening a database (which is already open), replacing the albumDB variable with a new sqlite3 * pointer. Then, GetArticlesCount is closing the database, and when you return to the first method, the albumDB pointer is now referencing a closed database handle. Thus subsequent SQL calls will generate SQLITE_MISUSE.
To avoid this problem, I would advise against having each function that performs SQL from opening and closing the database. Open the database once and then have all subsequent SQLite calls use that one sqlite3 * pointer.
Try to find error by using below code.
const char *sql = "INSERT INTO REPORTDATA (Num, Json) VALUES VALUES (?,?)"
if (sqlite3_prepare_v2(albumDB, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(#"Prepare failure: %s", sqlite3_errmsg(albumDB));
}
if (sqlite3_bind_text(statement, 1, [commentString UTF8String], -1, NULL) != SQLITE_OK)
{
NSLog(#"Bind 1 failure: %s", sqlite3_errmsg(albumDB));
}
if (sqlite3_step(statement) != SQLITE_DONE) {
NSLog(#"Step failure: %s", sqlite3_errmsg(albumDB));
}
sqlite3_finalize(statement);
As others suggested, I also recommend you to examine the actual error message.
9 of 10, I believe it is because the database file Album.db is not in the documents directory.
Try adding a breakpoint and check the databasePath value, open that directory and confirm the file is there.
If the file has 0 bytes of size, make sure to remove it and add the correct file to your Bundle Resources in:
Project -> Targets -> right target -> Build Phases -> Copy Bundle Resources
EDIT: In your case, you closed the database in GetArticlesCount and tried to use the database pointer after closing it. So I believe Rob's answer is the right solution.
I am trying to connect to ldaps server through through ldap_start_tls_s but i am continuously getting error -12(LDAP_INAPPROPRIATE_MATCHING).
Below is my code
const char*ldapServer=[#"ldaps://xx.xxx.xxx.xx" UTF8String];
LDAP *ld;
int rc;
/* Open LDAP Connection */
if( ldap_initialize( &ld, ldapServer ) )
{
perror( "ldap_initialize" );
}
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"server"
ofType:#"pem"];
NSString *newDir = [filePath stringByReplacingOccurrencesOfString:#"/server.pem" withString:#""];
int version = LDAP_VERSION3;
ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
// ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTFILE, [filePath UTF8String]);
// ldap_set_option(ld, LDAP_OPT_X_TLS_CERTFILE,NULL);
// ldap_set_option(ld, LDAP_OPT_X_TLS_KEYFILE, NULL);
// ldap_set_option(ld,LDAP_OPT_SSPI_FLAGS,0);
ldap_set_option(ld,LDAP_TIMELIMIT_EXCEEDED,[#"3000" UTF8String]);
ldap_set_option(ld,LDAP_OPT_REFERRALS,0);
ldap_set_option(NULL, LDAP_OPT_X_TLS_CTX, NULL);
ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR,[newDir UTF8String]);
rc = ldap_start_tls_s(ld, NULL, NULL);
if( rc != LDAP_SUCCESS )
{
printf("start tls failed.\n");
}
I am stuck with this can any one help me to sort this out. Thanks in advance..
I am getting an Unknown Error SQLite error when attempting to query my app's database with a select statement. I have gone over the code about a dozen times but it looks fine to me (obviously there is something wrong somewhere though).
Here is my code where the issue happen:
- (Boolean)loginAttempt
{
// Do any additional setup after loading the view.
//Startup Checks on Database
//Get Docs Directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
docDir = [dirPaths objectAtIndex:0];
//Build path to DB file
dbPath = [[NSString alloc] initWithString: [docDir stringByAppendingPathComponent: #"AGDB.sqlite"]];
//NSC
fManager = [NSFileManager defaultManager];
if ([fManager fileExistsAtPath: dbPath] == NO)
{
[self callAlert:#"Database Not Found!" :#"For some reason we could not find your Angles and Gridz Database. Let us know about this error right away!" :#"Ok"];
}
else
{
dbpath = [dbPath UTF8String];
}
if (sqlite3_open(dbpath,&dbCon) == SQLITE_OK)
{
const char *insertSQL = "select Password from Login where Username=?";
if (sqlite3_prepare_v2(dbCon,insertSQL,-1,&stmt,NULL) == SQLITE_OK)
{
if (sqlite3_bind_text(stmt,1,[user_Text.text UTF8String],-1,NULL) != SQLITE_OK)
{
sqlErr = [NSString stringWithUTF8String:sqlite3_errmsg(dbCon)];
return FALSE;
}
if (sqlite3_step(stmt) == SQLITE_ROW)
{
int cols = sqlite3_column_count(stmt);
if (cols > 0)
{
for (int i1 = 0; i1 < cols; i1++)
{
switch(i1)
{
case 2:
rPass = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(stmt,i1)];
break;
default:
break;
}
}
}
sqlite3_clear_bindings(stmt);
sqlite3_finalize(stmt);
sqlite3_close(dbCon);
//Check against supplied password
if (![rPass isEqualToString:pass_Text.text])
{
return FALSE;
}
else
{
return TRUE;
}
}
else
{
sqlErr = [NSString stringWithUTF8String:sqlite3_errmsg(dbCon)];
return FALSE;
}
}
else
{
sqlErr = [NSString stringWithUTF8String:sqlite3_errmsg(dbCon)];
return FALSE;
}
}
else
{
sqlErr = [NSString stringWithUTF8String:sqlite3_errmsg(dbCon)];
return FALSE;
}
}
It all looks correct to me. This is the only place in this .m file where the database is opened and in the other places within the app where it is opened I am finalizing any statements and closing the database connection once the operations on the database are finished being carried out.
It is able to find the database and the table as I had a different error just before this one stating that the Username column did not exist (it was actually Usename, typoed it while I was writing the select statement).
If anyone spots anything wrong with the code or knows of what might be causing this please let me know! Thanks.
I figured out what was going on. At first I was missing one level of SQL error checking. Instead that error checking was happening inside of the step statement block which should not have been returning the sql error message but returning a "database empty" message if the col count came back as 0.
Fixed that and one other problem where I should have been casing for 0 instead of 2 and that fixed this issue. The unknown error was being returned because there was no sql error message to return.
I'm building an iOS app using storyboards.I have integrated sqlite database in my app.
I'm unable to insert data into the table,i'm getting this error:
Failed to open db connection
I have created twoo more table with the same code that is working fine but this sports is my third table in which i'm getting this error.
here is my code
//SQLlite database code used to get file path
-(NSString *) getSportsFilePath {
NSString * docsPath= NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES)[0];
return [docsPath stringByAppendingPathComponent:#"sportsdb.db"];
}
-(int) createTable:(NSString*) filePath {
sqlite3* db = NULL;
int rc=0;
rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (SQLITE_OK != rc) {
sqlite3_close(db);
}
else {
char * query ="CREATE TABLE IF NOT EXISTS sportsselection (id INTEGER PRIMARY KEY AUTOINCREMENT, sportslist TEXT)";
char * errMsg;
rc = sqlite3_exec(db, query,NULL,NULL,&errMsg);
if (SQLITE_OK != rc) {
NSLog(#"Failed to create table rc:%d, msg=%s",rc,errMsg);
}
sqlite3_close(db);
}
return rc;
}
//SQLlite database code is used to insert data into the table
-(int) insert:(NSString *)filePath withName:(NSString *)sportslist {
sqlite3* db = NULL;
int rc=0;
rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE , NULL);
if (SQLITE_OK != rc) {
sqlite3_close(db);
NSLog(#"Failed to open db connection");
}
else {
NSString * query = [NSString stringWithFormat:#"INSERT INTO sportsselection (sportslist) VALUES (\"%#\")",sportslist];
char * errMsg;
rc = sqlite3_exec(db, [query UTF8String] ,NULL,NULL,&errMsg);
if (SQLITE_OK != rc) {
NSLog(#"Failed to insert record rc:%d, msg=%s",rc,errMsg);
}
sqlite3_close(db);
}
return rc;
}
- (void)viewDidLoad {
if ( _sports) {
for (int j=0;j< _sports.count;j++) {
int rc= [self insert:[self getSportsFilePath] withName: _sports[j]];
if (rc != SQLITE_OK) {
NSLog(#"Failed to insert record");
}
else
NSLog(#"Record is added");
}
}
}
You should log the return code that sqlite3_open_v2 returned to determine the cause of the error.
One way you could get the error you describe would be if you failed to call createTable before you called insert. Usually you would check for the existence of the file, and call createTable if it's not found. You don't appear to call createTable anywhere.
When I run my previous game against the 64 bit architecture, I get OpenAL errors..
It says "no matching function for call to alGenBuffers" and "no matching function for call to alGenSources". How can I fix these errors?
The whole method
-(bool) loadSoundWithKey:(NSString *)_soundKey File:(NSString *)_file Ext:(NSString *) _ext Loop:(bool)loops{
ALvoid * outData;
ALenum error = AL_NO_ERROR;
ALenum format;
ALsizei size;
ALsizei freq;
NSBundle * bundle = [NSBundle mainBundle];
CFURLRef fileURL = (__bridge_retained CFURLRef)[NSURL fileURLWithPath:[bundle pathForResource:_file ofType:_ext]];
if (!fileURL)
{
NSLog(#"file not found.");
return false;
}
outData = GameGetOpenALAudioData(fileURL, &size, &format, &freq);
CFRelease(fileURL);
if((error = alGetError()) != AL_NO_ERROR) {
printf("error loading sound: %xn", error);
exit(1);
}
NSUInteger bufferID;
alGenBuffers(1, &bufferID); // error
alBufferData(bufferID,format,outData,size,freq);
[bufferStorageArray addObject:[NSNumber numberWithUnsignedInteger:bufferID]];
NSUInteger sourceID;
alGenSources(1, &sourceID); // error
alSourcei(sourceID, AL_BUFFER, bufferID);
alSourcef(sourceID, AL_PITCH, 1.0f);
alSourcef(sourceID, AL_GAIN, 1.0f);
if (loops) alSourcei(sourceID, AL_LOOPING, AL_TRUE);
if (outData)
{
free(outData);
outData = NULL;
}
return true;
}
I have figured out..
Apparently alGenBuffers and alGenSources require GLuint not NSUInteger!