ipad - write NSString to text file - ios

I have text file text.txt in my xcode project and I need to write NSString init from my iOS app. I've tried this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: #"text.txt"];
NSString *content = #"Test";
[content writeToFile: docFile atomically: NO];
But it doesn't work for me... So can you help me with it?

this worked for me
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
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:#"%#/text.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"Test";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}

Related

How to find a file in Project?

I'm getting a problem to find a file from project. I am getting this file using code but I can't get it using url.
Please help me out from this problem.
Here is the path of file
Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents/file.txt
Here is the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *Path = [NSString stringWithFormat:#"%#/%#%#",documentsDirectory,#"file"#".txt"];
[str writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *fn=#"file";
NSString *searchFilename =[fn stringByAppendingString:#".txt"]; // name of the PDF you are searching for
NSArray *pathss = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorys = [pathss objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectorys];
NSString *documentsSubpath;
BOOL fileFound = false;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
fileFound=NO;
}
NSLog(#"found %#", documentsSubpath);
fileFound =YES;
}
if(fileFound){
NSLog(#"File Found");///this line is execute when i run this code
}
In code, you can use:
NSURL *fileURL = [NSURL URLWithPath: documentsSubpath];
And that will be the path to your file.
If you want to see the actual file, go to the Macintosh Finder and click "Go To Folder" (it's under the "Go" menu, or ⇧⌘G all together). Then type in your path MINUS the last path component, which is the filename. In your case, that is "/Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents".

How to store a NSData locally

I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this
NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"the converted string to nsdata is :%#",conData);
[conData writeToFile:#"Filename.txt" atomically:YES];
but unfortunately this is not working can any one help.
Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.
This writes file for me
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Filename.txt"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
you should pass a correct path in writeToFile method
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];
You have given only file name(Filename.txt) not whole file path thats why your code is not working.
Check below line of code you will get idea.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];

Image not access in iOS 6 from document library?

I have to access image from document library in iOS 6 .
strImgSign = [NSString stringWithFormat:#"%#/Documents//%#", NSHomeDirectory(),strImgSign];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *strImgSign = [[arrNameFinal objectAtIndex:indexPath.row] objectForKey:#"signimage"];
/var/mobile/Applications/D912ACC0-5B23-49B2-B9F1-E45ECD713553/Documents//docSign6167Feb13,2015-12.03.26.png
But image access in iOS 7,8 is perfect Working.
You should not build the directory from the NSHoneDirectory or use path separators in you string.
Correct way to build directories:
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
imagePath = [imagePath stringByAppendingPathComponent:strImgSign];
But even better and only correct way is to use the correct directory:
NSString *documentPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *imagePath = [documentPath stringByAppendingPathComponent:strImgSign];
There is an extra / in your path:
strImgSign = [NSString stringWithFormat:#"%#/Documents//%#", NSHomeDirectory(),strImgSign];
Change that to:
strImgSign = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(),strImgSign];
But as mentioned by #rckoenes, it's not the correct way of building file system paths. If your image is located in document directory you can use:
NSString *docDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *yourImagePath = [docDirectory stringByAppendingPathComponent:strImgSign];
But I'm not sure how it worked for you in iOS 7 and iOS 8
NSString *filename = [filepart lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString documentsDirectory = [paths objectAtIndex:0];
NSString inboxPath = [documentsDirectory stringByAppendingPathComponent:#"Inbox"];
NSString *filePath = [inboxPath stringByAppendingPathComponent:filename];

How to create a .txt file programmatically on iOS

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

How to Read a file from documents directory in iOS

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

Resources