I am having an app in which I have a folder named "Images" in my main bundle.
In This folder there is another folder called "Images1" containing some images.
When my app Launch I want the folder "Images" on the documents directory.
I want to fetch images from the folder "Images1".
But I can't get my images in the folder "Images" at documents directory with the following code.
Edited
BOOL success1;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
NSError *error1;
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:#"Images/Images1"];
success1 = [fileManager fileExistsAtPath:writableDBPath1];
if (success1) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images/Images1"];
NSLog(#"Default : %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
if (!success1) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error1 localizedDescription]);
}
Please help me.
Are you sure that you have the files in your folder tree?
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"/Images/Images1"];
usually when xcode make a package it flatten the directory contents. So first check you have all the things in your source folder. Even if you see that the folder is shown in your package explorer, when copied in the app, you will see the images are in the root folder. To avoid this, when you add the Image folder, in your xcode project, you can check the option to 'create folder reference'.
However, your write may fail because of an overwrite. In that case you have to implement a delegate method for NSFileManager given below.
- (void) copyFolder {
BOOL success1;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
fileManager1.delegate = self;
NSError *error1;
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:#"/Images"];
success1 = [fileManager1 fileExistsAtPath:writableDBPath1];
if (success1 )
{
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images"];
NSLog(#"default path %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
} else {
if (![[NSFileManager defaultManager] fileExistsAtPath:writableDBPath1])
[[NSFileManager defaultManager] createDirectoryAtPath:writableDBPath1 withIntermediateDirectories:NO attributes:nil error:&error1];
}
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
if ([error code] == 516) //error code for: The operation couldn’t be completed. File exists
return YES;
else
return NO;
}
Related
I have a framework that expects a .string file from the Project that it is imported to. How do I save a .string file from my app's [NSBundle mainBundle] to NSLibraryDirectory, and then have the framework read it from NSLibraryDirectory?
Thank you
Thanks #iOS_Developer for the writing part.
NSString *resourcepath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"filename.strings"];
NSString *filePath = [kSXBFileManLibraryDirectoryPath stringByAppendingPathComponent:#"filename.strings"];
Write:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if ([fileManager copyItemAtPath: resourcepath toPath:destination error:&error]){
NSLog(#"Copy Success");
}
else{
NSLog(#"Copy error: %#", error);
}
Read:
NSString *newPath = [kLibraryDirectoryPath stringByAppendingPathComponent:#"filename.strings"];
NSDictionary *contents = [NSDictionary dictionaryWithContentsOfFile:newPath];
NSLog(#"contents:%#", [contents objectForKey:#"login.background"]);
where;
#define kLibraryDirectoryPath [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject]
filename.strings
"login.background" = "FE8100";
"login.textField" = "FE8100";
"login.button" = "1B0D62";
You can get path to bundle Directory and Library directory and Move file from bundle to Library directory with CopyItemAtPath
NSArray *libraryPath=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directoryPath = [libraryPath objectAtIndex:0];
NSString *imagePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Templete.string"];
// Copy the image Folder from the package to the users filesystem
[fileManager copyItemAtPath:imagePathFromApp toPath:directoryPath error:nil];
when i use simulator,i can find the database file in /documents .but when i use my iPhone to run the project,i can not find the database file.
what time should i create the database file or use this code in my project?
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex:0];
NSString *dbFilePath = [documentFolderPath stringByAppendingString:DATABASENAME];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isExist = [fm fileExistsAtPath:dbFilePath];
if (!isExist) {
NSString *backupDbPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:DATABASENAME];
[fm copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];
}
For the first time or the database file does not exist in the documents directory, you have to copy DB file to document directory:
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
Ref: http://www.appcoda.com/sqlite-database-ios-app-tutorial/
You can't access the directories of iPhone or iPad. So even if you successfully created a database, you won't see it. You can judge its existence by read data from it.
I am creating a directory inside my application.Is there a code to view the contents of the directory in xcode. For example in android you can create a custom directory and view its contents using a file manager application. Can the similar procedure be done in apple?
Here is the code which i use to create a directory?
bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
fileManager = [NSFileManager defaultManager];
myImageDirectory = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
if ([myImageDirectory count] == 1){
NSLog(#"myImageDirectoryIs already present directory is already present");
}else{
directoryPath = [[myImageDirectory objectAtIndex:0] URLByAppendingPathComponent:bundleIdentifier];
NSLog(#"myImageDirectory directory name = %#",[directoryPath absoluteString]);
NSError *theError = nil;
if (![fileManager createDirectoryAtURL:directoryPath withIntermediateDirectories:NO attributes:nil error:&theError]){
NSLog(#"didnt write image data");
}else{
imagePath = [[directoryPath absoluteString] stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#_%#_%#_image.jpg",dIdNo,iIdNo,[self currentDateandTime]]];
[imageData writeToFile:imagePath atomically:YES];
}
}
If your app is running in the simulator you'll need to use Finder. Go to the following directory:
/Users/<username>/Library/Application Support/iPhone Simulator/<iOS version>/Applications/<uuid>/Library/Application Support
If your app is running on the device you can use Xcode:
Connect the device
Choose menu option Window -> Organizer
Go to the Devices Tab
Click Applications under the device menu on the left
Pick your Application
The directory contents will be listed and you can optionally download everything.
try this...
to create a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
to retrieve contents from directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *customDirectory = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:customDirectory error:&error];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",customDirectory,strFile];
if([[strVideoPath pathExtension] isEqualToString:#"mp4"] || [[strVideoPath pathExtension] isEqualToString:#"mov"])
{
[urlArray addObject:strVideoPath];
}
}
you can get the contents of the directory(MYNewFolder) from below code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"MYNewFolder"];
NSArray *filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:stringPath
error:nil];
for ( NSString *apath in filePathsArray )
{
NSLog(#"inside the file path array=%d",apath);
}
Method
-(NSArray *) getObjectsInDirectory:(NSString *)directory {
NSFileManager * fm = [NSFileManager defaultManager];
NSError * error = nil;
NSArray * result = [fm contentsOfDirectoryAtPath:directory error:&error];
return result;
}
How-To
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray * files = [self getobjectsInDirectory:documentsPath];
This code is used to get an array of the files within the documents directory.
Viewing the Files
NSLog(#"%#", files);
Check this class out, it allows you to simplify so many things in iOS: Atomic Class
I am working with the sqlite database and everything is going well. I added 4 entries in the table, and then added textview on my xib file. Now i want that this data should be fetched from the sqlite database which is placed in the bundle of the project. But i am not getting how to call this database from the bundle to thedirectory path. Please help me out regarding this issue.
Use this code:
First call this method which will check wheter dbfile is stored in documents Directory or not. If not It will write your file to documents directory.
-(void)openDatabase {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"databasefilename.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
error:&error];
if (!success)
NSLog(#"Failed to create writable database file with message '%#'.",
[error localizedDescription]);
}
}
- (NSString *) getDBPath {
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"databasefilename.sqlite"];
}
Then check in Appdelegate or any other class where you want:
if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
NSLog(#"database opened successfully");
}
I have created a myDB.sqlite database from SQLite Manager firefox addon. I want to add this myDB.sqlite file to my project. Then I can write functions to get data from tables.
I tried to add the myDB.sqlite file to project folder & create a filepath like this. But I think this filepath is wrong.
-(NSString *) filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"document.sqlite"];
return path;
}
Does it correct to add myDB.sqlite file to the project folder? or where should I save this myDB.sqlite file & what is the filepath I should use?
add your myDB.sqlite file in your project. by right click your project name=> add files to ""projectName", then add it.
to get your file path you can add this in your appDelegate
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(#"dbpath : %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"myDB.sqlite"];
}
in your did finish with launching method call [self copyDatabaseIfNeeded];
I assume you have successfully copied sqlite db into project's folder. So you have sqlite Database in your app's bundle now.
So you need to copy database from app's bundle to document directory of device/simulator using following code. Write these in AppDelegate.m
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
// First, test for existence.
if (![fileManager fileExistsAtPath:folderPath])
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
NSString *dbPath = [folderPath stringByAppendingPathComponent:#"document.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"document.sqlite : Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/** Database copy is not exist **/
[self copyDatabaseIfNeeded];
// Override point for customization after application launch.
return YES;
}
-(void)addSqlFileIfNotExists {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:#"document.sqlite"];
BOOL exits = [fileManager fileExistsAtPath:writableDBPath];
if(exits) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
BOOL exit = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!exit)
NSLog(#"%#",[error localizedDescription]);
}