read and writing from a file - objective-c

I know this may seem like a question that has been ask over and over again, but I am trying to verify that a file exists on the device (located in the supporting files folder) where the name of the file is "names.txt".
From what I've read the code below should work but I am continually getting "File not found."
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *path = #"names.txt";
if ([filemgr fileExistsAtPath:path]) {
NSLog (#"File exists");
}
else {
NSLog (#"File not found");
}

You need the full path to the file, not just the name.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportDirectory = paths[0];
NSString *path = #"names.txt";
NSString *fullPath = [appSupportDirectory stringByAppendingPathComponent:path];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:fullPath]) {
NSLog (#"File exists");
}
else {
NSLog (#"File not found");
}
Adjust this code to reflect the actual full path of the file in your app.

Related

How to get file from destination path

I dont know about how to open NSFileManager.
How to open NSFileManager in iPhone and upload document from NSFileManager please suggest any easy way.
How can open it and upload the document and also get the path for saved file.
Where I can find file physically.(Any location).
::EDIT::
I started coding in that year. so, i don't know about basic of NSFileManager.
Show contents:
NSLog(#"Documents directory: %#", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
Get all files
//get an instance of the File Manager
NSFileManager *fileManager = [NSFileManager defaultManager];
//we'll list file in the temporary directory
NSString * strPath = NSTemporaryDirectory();
//we'll need NSURL for the File Manager
NSURL *tempDirURL = [NSURL fileURLWithPath:strPath];
//An array of NSURL object representing the path to the file
//using the flag NSDirectoryEnumerationSkipsHiddenFiles to skip hidden files
NSArray *directoryList = [fileManager contentsOfDirectoryAtURL:tempDirURL
includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
Reference:http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files
http://nshipster.com/nsfilemanager/
An iPhone's documents directory is used for saving data. We can save some personal data like as file, image, video etc. The document's directory's data will remain in the iPhone's memory until the application is forcibly terminated.
Let's see an example of how to store some images & retrieve those images later in an iPhone.
// For saving the images in the Document's Directory
-(void)saveImagesInIPhone:(NSData*)imageData withName:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectoryPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NOattributes:nil error:nil];
//Add the FileName to FilePath
NSString *filePath = [folderPath stringByAppendingPathComponent:[iconName stringByAppendingFormat:#"%#",#".png"]];
//Write the file to documents directory
[imageData writeToFile:filePath atomically:YES];
}
Result:- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
///To retrieve the images from the document Directory
-(UIImage*)retrieveImageFromPhone:(NSString*)fileNamewhichtoretrieve
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
NSString *filePath = [folderPath stringByAppendingPathComponent:
[fileNamewhichtoretrieve stringByAppendingFormat:
#"%#",#".png"]];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
return [[UIImage alloc] initWithContentsOfFile:filePath];
else
return nil;
}
result :- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
You can get Directory Path like this..
-(NSString *)getDBPath
{
//Searching a standard documents using NSSearchPathForDirectoriesInDomains
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSLog(#"I am in --> getDBPath==%#",paths);
return [documentDir stringByAppendingPathComponent:#"abcd_DB.sqlite"];
}
**If you are using iOS Devices-
You can get Your DB directly by using https://macroplant.com/iexplorer Application.
**If you are using Simulator.
Get the Path directory
In terminal : open directory Path(Past your Directory Path).
Copy your DB and brows it with Firefox or sqlite browser.

Objective C strange if (NO) condition

I have facing a strange issue in Objective C. Please look at the code below.
+(BOOL)isWritableCopyofAppConfig{
BOOL response = false;
NSURL *urlConfig = [NSURL URLWithString:APP_CONFIG_PATH];
NSData *dataReturn = [NSData dataWithContentsOfURL:urlConfig];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"AppConfig.plist"];
if (dataReturn != nil ){
// It always goes here
}
else{
// Never reach here.
}
return response;
}
Even if I change the above if condition to the following:
if (NO){
// It always goes here even if there is NO.
}
else{
// Never reach here.
}
I tried cleaning the project i tried other things like directly comparing NO == YES still it goes inside the first block.
Does anyone knows how to solve this or what is this behavior?
EDIT: The entire code
+(BOOL)isWritableCopyofAppConfig{
BOOL response = false;
NSURL *urlConfig = [NSURL URLWithString:APP_CONFIG_PATH];
NSData *dataReturn = [NSData dataWithContentsOfURL:urlConfig];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"AppConfig.plist"];
if (NO){
if (filePath != nil){
response = [dataReturn writeToFile:filePath atomically:YES];
}
}
else{
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"AppConfig" ofType:#".plist"];
[fileMgr copyItemAtPath:resourcePath toPath:filePath error:nil];
}
return response;
}
Its a class method (called from AppDelegate.m):
AppConfigHandler.isWritableCopyofAppConfig();
EDIT: Screenshot of debugger

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

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.