how to add a file to my project programmatically - objective-c

I created a WinDef.plist file in the Application Support folder which contains default values.
I would like to add this file to my project without doing it manually.
Any idea how I could do it?
Ronald

Try following methods in your application didfinishlaunching method
-(void) checkAndCreateFile
{
//-------------------------------------------
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:cFilePath];
//-------------------------------------------
//File already there
if(success)
{
return;
}
//-------------------------------------------
//create file
NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:cfileName];
[fileManager copyItemAtPath:filePathFromApp toPath:cfilePath error:nil];
}
//------------------------------------------------------------------------
// Method : copyFile
// Method to create file
//------------------------------------------------------------------------
-(void) copyFile
{
cfileName = #"WinDef.plist";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentsPaths objectAtIndex:0];
cfilePath = [documentDir stringByAppendingPathComponent:cfileName];
[self checkAndCreateFile];
}
This will save WinDef.plist file in your application document folder if you want
And if you want to access that file values then you can retrieve it by using following code
NSString *path = [[NSBundle mainBundle] pathForResource: #"WinDef" ofType: #"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile: path];
id obj1 = [dictionary objectForKey: #"YourKey"];
This will give you that key value in dictionary

Related

Page Control and table view

I have ios app that contains 7 table view with different data. I fill each table from plist file and I need to have page control and in each page I need one table view. I put the page control , the table which I put it in the first page didnt change I saw it in other pages. How can I determine number of pages and content for each page? I put this
- (void)viewDidLoad
{
[super viewDidLoad];
int page=pageControl.currentPage;
//pageControlList=[[NSArray alloc]initWithObjects:tabelView,tabelViewq, nil];
pageControlBeingUsed = NO;
self.scrollView.contentSize = CGSizeMake(960, 424);
self.tabelView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
NSError *err;
for (page=0; page<7; page++) {
switch ([pageControl currentPage]) {
case 0:{
NSFileManager *fileManager = [NSFileManager defaultManager];
//getting the path to document directory for the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentDir = [paths objectAtIndex:0];
NSString *path = [documentDir stringByAppendingPathComponent:#"News.plist"];
//checking to see of the file already exist
if(![fileManager fileExistsAtPath:path])
{
//if doesnt exist get the the file path from bindle
NSString *correctPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"News.plist"];
NSLog(#"plist exist");
//copy the file from bundle to document dir
[fileManager copyItemAtPath:correctPath toPath:path error:&err];
}
// read data from plist file
presedients=[[NSMutableDictionary alloc]initWithContentsOfFile:path ];
Names=[presedients objectForKey:#"Name"];
url=[presedients objectForKey:#"URL"];
NSLog(#"%#",presedients);
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
}
break;
case 1:{
pageControl.currentPage =pageControl.currentPage+1;
NSFileManager *fileManager = [NSFileManager defaultManager];
//getting the path to document directory for the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentDir = [paths objectAtIndex:0];
NSString *pathq = [documentDir stringByAppendingPathComponent:#"Quran.plist"];
//checking to see of the file already exist
if(![fileManager fileExistsAtPath:pathq])
{
//if doesnt exist get the the file path from bindle
NSString *correctPathq = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Quran.plist"];
NSLog(#"plist exist");
//copy the file from bundle to document dir
[fileManager copyItemAtPath:correctPathq toPath:pathq error:&err];
}
// read data from plist file
presedientsq=[[NSMutableDictionary alloc]initWithContentsOfFile:pathq ];
NamesQ=[presedientsq objectForKey:#"Name"];
urlq=[presedientsq objectForKey:#"URL"];
NSLog(#"%#",presedientsq);
}
break;
but the program see case one (which I put the first table and appear in all the pages). Why? Is my condition is wrong?
Regards

Error writing to plist in documents directory

I use the following code to copy a Resources plist file into the documents directory:
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Test-Info.plist"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:#"Test-Info.plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
NSLog(#"Test-Info.plist successfully copied to DocumentsDirectory.");
}
I get the success message, which is great. I'm assuming it's been copied correctly into the documents folder.
However when I then try to read and write to the saved plist file it returns null:
Key entry in Test-Info.plist:
Key: EnableEverything
Type: Boolean
Value: YES
Write code:
NSString *adKey = #"EnableEverything";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:#"Test-Info.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
NSString *enableEverything = [[plist valueForKey:adKey] stringValue];
NSLog(#"****** EXISTING: %# ******", enableEverything); // returns (null)
// Disable in plist.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
NSString *enableEverything1 = [[plist valueForKey:adKey] stringValue];
NSLog(#"****** NOW: %# ******", enableEverything1); // returns (null)
Output:
****** EXISTING: (null) ******
****** NOW: (null) ******
My question is why are they (null) when they exist within the plist file?
You are trying to mutate an immutable object.
You need a NSMutableDictionary.
IE
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];
Also check, if the plist object isnt nil, as any messages can be send to nil without raiing an error. this wouldnt fail, also nothing actually happens.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
as the source path is nil, you are most like not copying the file during compilation bundling. drag it here:
Try this for nsbundle path for resource
NSString *path= [[NSBundle mainBundle] pathForResource:#"SportsLogo-Info" ofType:#"plist"];
Try allocating
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:path]];
Also check if the file has been copied or not. Go to Library=>Application Support=>iPhone Simulator=>folder named your version of simulator iOS=>Applications=>Find the right folder of your project=>Documents see if the plist file is there

Copy file to App Document folder automatically

I want to copy set of files from project resource folder to the app document folder automatically at the time of app first launch. Can I do this. Do I need to do it through the code.
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Data.txt"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"txt"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
}
In application did finish launching with options

Can't find the database file

I can't figure why db.sqlite can't be found. I added it to the resource dir of the project. It is there.
Here is some code how I check for existing.
-(void)getDatabaseLocation
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"db.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
NSLog(#"NO"); // It's say no when this method is called.
}
else
{ NSLog(#"YES");
}
}
//EDIT
Now I check that the path in docsDir doesn't exist.
Of course it isn't there. You must first copy the resource to the documents directory, like this:
if (![filemgr fileExistsAtPath:databasePath])
{
[filemgr copyItemAtPath:[NSBundle.mainBundle pathForResource:#"db" ofType:#"sqlite"] toPath:databasePath error:nil];
}
EDIT: If you only need to do lookups on the database (no editing), then you can simply do this:
databasePath = [NSBundle.mainBundle pathForResource:#"db" ofType:#"sqlite"];

SQLite Step Failed: attempt to write a readonly database , using wrapper

I keep getting an error "SQLite Step Failed: attempt to write a readonly database" when using this code to copy a database:
-(void)createEditableCopyOfDatabaseIfNeeded
{
// Testing for existence
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath =
[documentsDirectory stringByAppendingPathComponent:#"Money.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to
// the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"Money.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with Message : '%#'.",
[error localizedDescription]);
}
}
I am using the above code in AppDelegate
and this:
NSString *writableDBPath =
[[NSBundle mainBundle] pathForResource:#"Money"
ofType:#"sqlite"];
In ViewController.m
I am using http://th30z.netsons.org/2008/11/objective-c-sqlite-wrapper/ what am I doing wrong?
This is happening again and again... It was working fine before but again the problem started.
The problem is that you cannot write anything to your bundle. To be able to change your database you need to copy it to application's documents or caches folder and work with that copy.