I am trying to write a simple log file for each execution of my app. The logfile name is based on the current time and is stored in the app directory. The code below is what I am trying which works on the simulator but when I execute on an iPad it fails with 'Operation not permitted' (EPERM in errno.h).
-(BOOL)CreateLogFile
{
mLogFilePath = [self GetLogFileNameForTimeNow];
BOOL Success = [[NSFileManager defaultManager] createFileAtPath:mLogFilePath contents:nil attributes:nil];
/*BOOL Success = [[NSFileManager defaultManager] createFileAtPath:mLogFilePath contents:nil attributes:[NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey]];*/
if ( Success )
{
NSLog( @"Successfully created file: %@", mLogFilePath );
mLogFileHandle = [NSFileHandle fileHandleForWritingAtPath:mLogFilePath];
[self WriteInstanceInformationToLog];
}
else
{
NSLog( @"Failed to create file: %@ %s", mLogFilePath, strerror(errno) );
}
return Success;
}
I tried the commented out code too but that also fails. I am new to iOS programming so might be missing something basic. Anyway the output form the above shows the following on iPad:
2013-05-10 14:54:51.794 RichTest1[128:907] Failed to create file:
/var/mobile/Applications/XXXX/RichTest1.app/20130510145451.log Operation not permitted
but on the simulator it works:
2013-05-10 15:07:14.696 RichTest1[1604:c07] Successfully created file:
Users/abruce/Library/Application Support/iPhone Simulator/6.1/Applications/XXXX/RichTest1.app/20130510150714.log
Where am I going wrong?
--edit
Here is the code for the GetLogFileNameForTimeNow
-(NSString*)GetLogFileNameForTimeNow
{
NSString* FileName = [NSString stringWithFormat:@"%@.log", [self GetTimeAsString] ];
NSString* AppFolderPath = [[NSBundle mainBundle] resourcePath];
return [NSString stringWithFormat:@"%@/%@", AppFolderPath, FileName];
}
-(NSString*)GetTimeAsString
{
return [mDateFormatter stringFromDate:[NSDate date]];
}
and the date formatter is setup as follows in the constructor of my class:
mDateFormatter = [[NSDateFormatter alloc] init];
NSString* DateFormat = @"yyyyMMddHHmmss";
[mDateFormatter setDateFormat:DateFormat];
You are trying to create a file inside app bundle, which is read-only on the device. Put your files into Documents or Library directories of the application.