Cant create a database in a specific folder in ios - iphone

I am working on a jailbroken device and I am not developing for the app store.
I create a database in my code in the beginning using this code.
if(temporaryvariable == 0 ) {
if (![[NSFileManager defaultManager]fileExistsAtPath:#"/Library/Myapp/Storage"]) {
NSLog(#"Creating Direcotory Documents");
[[NSFileManager defaultManager] createDirectoryAtPath:#"/Library/Myapp/Storage" withIntermediateDirectories:YES attributes:nil error:nil];
}
storeURL = [NSURL fileURLWithPath:#"/Library/Myapp/Storage/my.sqlite" isDirectory:NO];
} else {
storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"my.sqlite"];
}
The code works fine if I change the db path to root/var/mobile/documents. But when I use the path given in the above code the app crashes with the following error.
Unresolved error Error Domain=NSCocoaErrorDomain Code=256 "The
operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x334a30
{NSUnderlyingException=authorization denied, NSSQLiteErrorDomain=23}
,,, {
NSSQLiteErrorDomain = 23;
NSUnderlyingException = "authorization denied"; } with store url file://localhost/Library/Myapp/Storage/my.sqlite
Abort trap: 6
I even tried changing the permissions of the storage folder but it doesn't work. Help me with this error please
EDIT:
This folder is actually the main bundle of my application on the jailbroken iphone.

Related

ios not finding a txt file using stringWithContentsOfFile

I have a text file thetext.txt. Which is in my project and is copied on build, in build settings. In the same way that my GL shaders and textures are (which work fine.)
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:#"thetext.txt"
encoding:NSUTF8StringEncoding
error:&errorReading]
componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
It prints the following to console.
Reading error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x896fff0 {NSFilePath=thetext.txt, NSUnderlyingError=0x896ff60 "The operation couldn’t be completed. No such file or directory"}
Have I missing something?
This fails because you are passing the file name and not the path to the file. Try something like this
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"thetext" ofType:#"txt"];
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&errorReading]
componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
Hopefully there will be no error!

"The operation couldn’t be completed. (Cocoa error 512.)"

I have this code, which should be working perfectly, but I can't udnerstand why it isn't:
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Images/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
BOOL directoryExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (directoryExists) {
NSLog(#"isDirectory: %d", isDirectory);
} else {
NSError *error = nil;
BOOL success = [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
if (!success) {
NSLog(#"Failed to create directory with error: %#", [error description]);
}
}
NSString *name = [NSString stringWithFormat:#"%#.jpg", [JEntry generateUuidString]];
NSString *filePath = [path stringByAppendingPathComponent:name];
NSError *error = nil;
BOOL success = [fullImageData writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(#"Failed to write to file with error: %#", [error description]);
}
return filePath;
}
It passed the directoryExists without an error, but when it gets to writeToFile, it gives me this error:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x5634ee0 {NSFilePath=/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/18DAE0BD-6CB4-4244-8ED1-9031393F6DAC.jpg, NSUnderlyingError=0x5625010 "The operation couldn’t be completed. Not a directory"}
Any ideas why this might be?
I was able to reproduce your error when writing a file first in the path #"Documents/Images/", then trying to write the image using your code.
I think there are two possible scenarios for this:
1) You created that file by mistake at a previous execution of your app. This will be solved if you reset the simulator using the menu: iOS Simulator > Reset Contents and Settings, and uninstalling the app from your device: Long press > click on the x symbol.
2) There is some code somewhere else in your app that creates this file. If this is the case, you should find this code and remove it.
From FoundationErrors.h:
NSFileWriteUnknownError = 512
Try using withIntermediateDirectories:YES.
In my case a period '.' in the directory name (e.g. ~/Documents/someDir.dir/somefile) was the cause of the problem. I removed the offending character and the error disappeared.

Copying file from bundle to documents not working (Cocoa error 512)

I am trying to simply copy my sqlite3 database to the documents directory. I get a Cocoa Error 512 and what I figured about that is, that it's not a valid directory (or something like that.
The database file is in my Resources folder in XCode. (The name of file is correct)
Here is the code I am trying to use:
-(void) checkAndCreateDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
//databasePath + databaseName is declared in the header
databaseName = #"WaypointDatabase.sql";
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
success = [fileManager fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Database exists");
return;
}
else
NSLog(#"Database does not exists");
NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:#"WaypointDatabase" ofType:#"sql"];
if(databasePathFromApp == nil)
{
NSLog(#"ERROR: IT IS NIL");
}
NSError* error = nil;
NSLog(#"Path in bundle:\n%#\n\n", databasePathFromApp);
NSLog(#"Path to copy to:\n%#\n\n", databasePath);
[fileManager copyItemAtPath:databasePathFromApp
toPath:databasePath error:&error];
[fileManager release];
if (error)
{
NSLog(#"%#\n\n", error);
NSLog(#"%#", [error userInfo]);
}
}
And the output to console that I get is:
2011-10-30 10:36:13.242 xxxx[6726:707] Database does not exists
2011-10-30 10:36:13.249 xxxx[6726:707] Path in bundle:
/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/xxxx.app/WaypointDatabase.sql
2011-10-30 10:36:13.252 xxxx[6726:707] Path to copy to:
/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/Documents/WaypointDatabase.sql
2011-10-30 10:36:13.268 xxxx[6726:707] Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0xe8b7cd0 {NSUserStringVariant=(
Copy
), NSFilePath=/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/xxxx.app/WaypointDatabase.sql, NSDestinationFilePath=/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/Documents/WaypointDatabase.sql, NSUnderlyingError=0xe8b7ee0 "The operation couldn’t be completed. Not a directory"}
2011-10-30 10:36:13.272 xxxx[6726:707] {
NSDestinationFilePath = "/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/Documents/WaypointDatabase.sql";
NSFilePath = "/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/xxxx.app/WaypointDatabase.sql";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=20 \"The operation couldn\U2019t be completed. Not a directory\"";
NSUserStringVariant = (
Copy
);
}
I figure this must be to do with getting the directory paths or something, but have been stuck on this for a few days now.
Take note, this works perfectly & without any errors on the simulator.
Where could I have gone wrong?
[UPDATE]
Could this be because the Documents-folder directory does not exist? How would I go about to create/check it?
[UPDATE 2]
I have done some other tests using
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err = nil;
NSArray *dirArr = [fileManager contentsOfDirectoryAtPath:documentsDir error:&err];
NSLog(#"~~Contents:\n%#",dirArr);
NSLog(#"~~Error: \n%#",err);
And surprisingly it gave Cocoa Error 256 and also said "Not a directory". It is almost as if the Documents directory does not exist. But it does, according toNSSearchPathForDirectoriesInDomains`
Here is the output I got
2011-10-30 10:59:16.934 xxxx[6774:707] ~~Contents:
(null)
2011-10-30 10:59:16.936 xxxx[6774:707] ~~Error:
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x10052580 {NSUserStringVariant=(
Folder
), NSFilePath=/var/mobile/Applications/FF654016-4257-47BB-99FE-55DB5453BBC6/Documents, NSUnderlyingError=0x10054a50 "The operation couldn’t be completed. Not a directory"}
The problem got solved by setting a non standard Bundle ID in die info.plist
I used the Bundle ID from iTunes Connect for this specific app. Now everything works perfectly.
Try changing
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
for
[[NSBundle mainBundle] pathForResource:#"WaypointDatabase" ofType:#"sql"];
and check that this does not return nil to ensure that the is not what's going wrong apart from that it looks fine to me on first skim.

Using exportAsynchronouslyWithCompletionHandler

I try to export an audio file from the iPod-Library. I want to create with this iPod-Library file an new file. In the AV Foundation Programming Guide in chapter Reading and Writing Assets there is a little example. However this code doesn't work for me. 4 errors happens
Export Status 4 Error Domain=AVFoundationErrorDomain
Code=-11800 "The operation could not be completed"
UserInfo=0x1edfa0 {NSLocalizedFailureReason=An unknown error occurred (-12124),
NSUnderlyingError=0x1ebdc0 "The operation couldn’t be completed. (OSStatus error -12124.)",
NSLocalizedDescription=The operation could not be completed}
My code
AVURLAsset *objAvUrlAsset = [[AVURLAsset alloc] initWithURL:[tempArray objectAtIndex:0] options:nil];
NSLog(#"%s objAvUrlAsset %#", __FUNCTION__, objAvUrlAsset);
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:objAvUrlAsset];
NSLog(#"%s compatiblePresets %#", __FUNCTION__, compatiblePresets);
if ([compatiblePresets containsObject:AVAssetExportPresetAppleM4A]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:objAvUrlAsset presetName:AVAssetExportPresetAppleM4A];
NSString * exportPath = [NSString stringWithFormat:#"testTrack1.M4A"];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = AVFileTypeAppleM4A;
exportSession.shouldOptimizeForNetworkUse = YES;
NSLog(#"%s export Session %#",__FUNCTION__, exportSession);
[exportSession exportAsynchronouslyWithCompletionHandler: ^(void) {
// export completed
NSLog(#"Export Status %d %#", exportSession.status, exportSession.error);
}];
[exportSession release];
}
the nslog message
-[MyLocalMusicLibrary getAllTracks] objAvUrlAsset AVURLAsset: 0x1dd5a0, URL = ipod-library://item/item.mp3?id=-212958261728896866
-[MyLocalMusicLibrary getAllTracks] compatiblePresets (
AVAssetExportPresetAppleM4A,
AVAssetExportPreset960x540,
AVAssetExportPresetLowQuality,
AVAssetExportPresetMediumQuality,
AVAssetExportPreset640x480,
AVAssetExportPresetHighestQuality,
AVAssetExportPreset1280x720
)
-[MyLocalMusicLibrary getAllTracks] export Session AVAssetExportSession: 0x1e85c0,
asset = AVURLAsset: 0x1dd5a0, URL = ipod-library://item/item.mp3?id=-212958261728896866,
presetName = AVAssetExportPresetAppleM4A, outputFileType = com.apple.m4a-audio
-[MyLocalMusicLibrary getAllTracks] Export Status 4 Error Domain=AVFoundationErrorDomain
Code=-11800 "The operation could not be completed"
UserInfo=0x1edfa0 {NSLocalizedFailureReason=An unknown error occurred (-12124),
NSUnderlyingError=0x1ebdc0 "The operation couldn’t be completed. (OSStatus error -12124.)",
NSLocalizedDescription=The operation could not be completed}
How can i fix this four errors. Do i need for this export the AVAssetReader and AVAssetWriter.
I got the same result from AVAssetExportSession, what the completely useless NSError is trying to tell you is that the path you're exporting to doesn't fully exist. You'll want to make sure that you create the path to the directory you're placing the file in using NSFileManager.
The problem for me was that I was trying to convert the file directly from the tmp directory after getting it from the UIImagePickerController
What I had to do was first save the file to the Library, then iterate over the ALAssetLibrary files to find the latest video saved. Then I converted that video to .mp4 and stored it int he application's local documents directory for use as I please.
Kind of ridiculous that this is necessary but it works.

Error when trying to deleting a file that exist

A tester said that he got this message only once, and I can't seem to reproduce it or figure out how this message appeared. In a nut shell, my application starts a background thread and grabs data from our server. Once we are done downloading the data we store it in an xml file, so we can grab the data from this file incase we shutdown durning the parsing of the xml. Once I am done parsing the xml I delete the file. Here is my code for deleting.
-(void)deleteSavedXmlServerData
{
AppDelegate_Shared* appDelegate = (AppDelegate_Shared*)[[UIApplication sharedApplication] delegate];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileToLoad = [NSString stringWithFormat:#"%#/%#/upload.xml", [paths objectAtIndex:0], appDelegate.userId];
if([[NSFileManager defaultManager] fileExistsAtPath:fileToLoad] == YES)
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:fileToLoad error:&error];
if(error != nil)
{
eNSLog(#"%s Error Parsing old data: %# info: %#", __PRETTY_FUNCTION__, error, [error userInfo]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem With Syncing"
message:#"Problem reading in old data."
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
Everything seems to work perfectly, and it is not a big deal if this file does not get deleted. But I am confused why I would have an issue with deleting this file.
When I checked what the error message was this is what I got this.
-[ServerSync deleteSavedXmlServerData] Error Parsing old data: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x11f3ed60 "Operation could not be completed. (Cocoa error 4.)" info: {
NSFilePath = "/var/mobile/Applications/CD181518-512F-4A0E-82ED-C438886E4A1D/Documents/71BD9A11-A604-6001-549C-DF6582F60124/upload.xml";
NSUserStringVariant = Remove;
}
If anyone know why if my file exist and I created it, why I cannot delete it?
Update
The question that confused me the most, is why does the first if statement say the file exist, but the error message that I get from trying to remove the file says that my file does not exist?
Reading the documentation for NSFileManager (don't know if I just missed it the first time), it says to not use the singleton method [NSFileManager defaultManager] because NSFileManager is not thread safe. I have not had this problem since then.
It looks like the document directory path is /.../71BD9A11-A604-6001-549C-DF6582F60124CD181518-512F-4A0E-82ED-C438886E4A1D/Documents/71BD9A11-A604-6001-549C-DF6582F60124. It should end in /Documents.
Googling for NSCocoaErrorDomain gives NSFileNoSuchFileError = 4.
Testing for file existence before removing it suffers from a race condition as another thread can come in and remove it before the deletion code executes. It would be better to refactor your code to remove the file first and ignore any "errors" related to file not found.
BTW: the answer regarding [NSFileManager defaultManager] not being thread safe is not entirely true. It is thread safe except when using a delegate for notifications.
According to this answer
NSFileManager: removing item
we need to have a file:// prefix. You can use [NSURL fileURLWithPath:] to achieve it.
For swift use NSURL(fileURLWithPath: realmPath)