Read/Write .string files from/to Directory - ios

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];

Related

View the contents of Custom Directory in iOS

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

add Separate .sqlite file to ios project

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]);
}

updating child plist programittically shown in simulator but not in device

I am implementing setting bundle first time and I have done it by creating Root.plist and Child.plist in Settings.bundle and have some fields in these plist.
I need to update the fields (add or remove) of Child.plist according to web services and I have written code for that in appdelegate. Its working fine in simulator (all fields are updated accordingly) but its not working in device.
Can any one suggest me what could be the reason of it.
code to copy plist to document directory and update that (as per the asnwer)
NSString *bundle = [[NSBundle mainBundle]pathForResource:#"Settings" ofType:#"bundle"];
NSString *path = [bundle stringByAppendingPathComponent:#"Category.plist"];
NSMutableDictionary *dictOfPlist = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableArray *dictArray = [dictOfPlist valueForKey:#"PreferenceSpecifiers"];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path1 = [documentsDirectory stringByAppendingPathComponent:#"Child.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path1])
{
[fileManager copyItemAtPath:path toPath: path1 error:&error];
}
for (some condition)
{
// creating dictionary
// add dictionary to array dictArray
}
[dictOfPlist setObject:dictArray forKey:#"PreferenceSpecifiers"];
[dictOfPlist writeToFile:path1 atomically:YES];
I think you have a problem to write your PLIST. You need to copy your PLIST from your resources bundle into the documents directory and modify the PLIST inside this folder.
For that you can use this piece of code :
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#”data” ofType:#”plist”];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
Have a look here.

Copy Folder from main bundle to documents directory in iphone

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;
}

Delete image from app directory in iPhone

I want to delete an image from my iPhone app.
I use the method below, passing the name of the image as an argument.
The problem is that the image isn't deleted.
- (void)removeImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#.png", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed: %#", fullPath);
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSLog(#"Directory Contents:\n%#", [fileManager directoryContentsAtPath: appFolderPath]);
}
The last two lines show the content in my app directory and the image I want to delete is still there. What am I doing wrong?
You are trying to delete a file in the Documents directory. You then read the contents of the bundle resources directory. These are not the same directory.
If you're trying to delete a file in the Documents directory, the you should rad that directory in your NSLog() at the end. If you're trying to delete a file inside your bundle, this is impossible. App bundles are signed and cannot be modified.
your code looks ok, so try adding some 'NSError' object to you code:
- (void)removeImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#.png", fileName]];
NSError *error = nil;
if(![fileManager removeItemAtPath: fullPath error:&error]) {
NSLog(#"Delete failed:%#", error);
} else {
NSLog(#"image removed: %#", fullPath);
}
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSLog(#"Directory Contents:\n%#", [fileManager directoryContentsAtPath: appFolderPath]);
}
In the code above I passed a NSError the error parameter of removeItemAtPath. If the system can't delete the file, this method will return NO and fill the error object with the error raised.
Based on your comment I found out that you are trying to delete the default.png and replace it with another one. Unfortunately, this is impossible. The image default.png is a part of your application bundle, which cannot be modified once it has been created and signed (this is a security measure from Apple, so applications cannot change after they have been reviewed). The only locations where you can create and delete files is inside the sandbox given to your application (the Documents folder).

Resources