I created an app to save as an csv file, app works fine in iOS simulator with both write and read. When i load the app to iOS device it doesn't data.
- (IBAction)saveInfo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:#"%#,%#,%#\n",
self.food.text,
self.movies.text,
self.channel.text];
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
//resultView.text = docPath;
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
resultView.text = filename;
if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
{
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filename];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
self.food.text = nil;
self.movies.text = nil;
self.channel.text =nil;
NSLog(#"Info saved");
}
- (IBAction)viewInfo:(id)sender {
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
NSString *fileContent=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
resultView.text = fileContent;
}
You are building the path incorrectly. Use:
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendinPathComponent:#"result.csv"];
The code you have results in a path like <path to app bundle>/Documentsresult.csv and on the device you can't write to the app bundle.
On Button action u can write below code maybe File will be displayed in my point of view its running correctly you should tray.....
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFile = [docsDir
stringByAppendingPathComponent: #"datafile.csv"];
NSLog(#"%#",dataFile);
NSData *data = [filemgr contentsAtPath:dataFile];
NSString *fooString=#"----------------\n Full File Data \n ---------------- \n " ;
fooString = [fooString stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ];
self.FileTextView.text=fooString;
Related
I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.
Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.
NSError *error;
NSString *stringToWrite = #"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
And to retrieve the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
I hope this help's you
-(void)writeToTextFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = #"This is Demo";
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)ShowContentlist{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
[content release];
}
This is the code I'm using and it works in simulator but showing nothing in idevice. If I add an folder or a file through ifunbox it shows up in device though. Do I need any permission to create or add files?
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"/Folders/%#", self.txtFolder.text]];
NSLog(#"%#", dataPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
[sec1Contents addObject:self.txtFolder.text];
sec1 = [NSArray arrayWithArray:sec1Contents];
[self.tblFiles reloadData];
}
thanks in advance.
Use this code :
NSURL *allitemsImageurl =[NSURL URLWithString: url];
NSData *allItemsImageData = data1; // Load XML data from web
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectoryPath = [paths objectAtIndex:0];
NSString *st1=[ #"img_" stringByAppendingString:[NSString stringWithFormat:#"%d.png",imageCount]];
NSString *allitemsImagePath = [documentsDirectoryPath stringByAppendingPathComponent:st1];
NSLog(#"%#",allitemsImagePath);
[allItemsImageData writeToFile:allitemsImagePath atomically:TRUE];
I want to create a file in my application document folder and i have to store some content. That content takes from my localhost file. So i write a below code. But this code didn't create a file in my application document folder.
- (void) createFile
{
NSString *strPath = [NSString stringWithFormat:#"http://192.168.5.117/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"File Exists");
}
else
{
NSLog(#"File not exists");
}
NSString *content = [NSString stringWithFormat:#"%#",data];
[content writeToFile:strLastpath atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
}
While build for running i got this.
2013-10-11 11:36:38.833 SampleFileCreation[1321:c07] Path : http://192.168.5.117/~mac/banana.obj
File Name : Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] Database Path : /Users/mac/Library/Application Support/iPhone Simulator/6.1/Applications/4FA749DF-D12D-4956-AF76-140D2F981F17/Documents/Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] File not exists
You can also try this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileName = #"yourFileName";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/fileName"];
NSDate *data = [NSData dataWithContentsOfURL:YourUrl]; // get date form url
[data writeToFile:dataPath atomically:YES]; // save data in file
I found the answer. File created successfully.
- (void) createFile {
NSString *strPath = [NSString stringWithFormat:#"http://-.-.-.-/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
docsDir=[docsDir stringByAppendingString:#"/Object File"];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSError *theError = nil;
NSFileManager *filemgr = [NSFileManager defaultManager];
**//I added this line**
[filemgr createDirectoryAtPath:docsDir
withIntermediateDirectories:YES
attributes:nil
error:&theError];
**//Changed this line**
[data writeToFile:[docsDir stringByAppendingPathComponent:strLastpath]
options:NSDataWritingAtomic
error:&theError];
if ([filemgr fileExistsAtPath:[docsDir stringByAppendingPathComponent:strLastpath]]){
NSLog(#"File Exists");
} else {
NSLog(#"File not exists");
NSLog(#"Tell Me error %#",[theError localizedDescription]);
}
}
I need to search a file in documents directory of iOS but i don't know the extension of that file. How to search the file without extension.
Below is the code if you know the filename.extension(abc.txt). How can i search for the same file with jsut filename(abc)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"abc.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *fileWithExt = nil;
for (NSString *file in directoryContent )
{
if([file stringByDeletingPathExtension] isEqualsTo:#"abc"]
{
fileWithExt = file;
break;
}
}
P.S. : The fileWithExt will contain the first file with name abc
Im trying to create an folder in user library directory,but its not creating. Is there any mistake in the below code.
databaseName = #"KITSMAW0051_DB.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
databasePath = [[documentsDir stringByAppendingPathComponent:folder ] stringByAppendingPathComponent:databaseName];
Ok first of all databasePath describes a path to a file not a directory. But let's say you actually want to create "Swasstik" folder inside user's Library:
// Your code
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
// I edited here to keep only the folder
NSString *folderPath = [documentsDir stringByAppendingPathComponent:folder];
// At this point we got the path to the folder
// but we want to actually go on and create it
// NSFileManager to the rescue!
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath: folderPath
withIntermediateDirectories: NO
attributes: nil
error: nil];
Of course you can study and set the manager as you like and also implement some error handling. I hope that this makes sense...
databaseName = #"KITSMAW0051_DB.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = [documentsDir stringByAppendingPathComponent:#"Swasstik"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]) {
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error != nil) {
NSLog(#"Some error: %#", error);
return;
}
NSString *databasePath = [folder stringByAppendingPathComponent:databaseName];