I want to create a .json file and .text file public so that it can be read by NSItemProvider. I want to create file programmatically.
Can you refer this link, that will be helpful to play around file creation, deletion etc...
http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files
Use the following code to write/create a .txt file in your app's Documents directory :
NSError *error;
NSString *stringToWrite = #"hello>!!new file created..";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
To read/fetch the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
Related
In my application, creating functionality in which require to upload document of type (pdf/xls/doc/image). After uploading the document that document name should show in screen and on click of that document it show the document which i have selected.
How to implement this functionality, which is the best practise to do this.
Plz provide your feedback.
You can create file using below code. Here it is txt file.
NSString *stringToWrite = #"This is my string";
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"filename.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Here i am reading and writing a json file.
Reading is done correctly but while i am writing a file it doesn't write data in json file.
Here is my code.
//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bookmark" ofType:#"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=#{#"index":#"1.1.1.1",#"text":#"Header",#"htmlpage":#"page_name"};
//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];
//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];
NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];
//now i write json file.....
[saveBookmark writeToFile:#"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];
In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.
Please help me with this......
EDIT: As correctly pointed out by #IulianOnofrei, use the document directory to read/write files and not the resources directory.
Use these methods to read and write data, and your problem should be solved:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
Code courtesy from another SO answer found here: Writing and reading text files on the iPhone
And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.
Hope this helps.
How would I go about creating a new text file in my program so that I can write content to it? I already understand how to write content but I haven't been able to find anything (anything easy to understand) on the subject.
Use this method:
+ (id)stringWithContentsOfFile:(NSString *)path
usedEncoding:(NSStringEncoding *)enc
error:(NSError **)error
An example:
NSString* path = [[NSBundle mainBundle] pathForResource:#"Example"
ofType:#"txt"];
NSError *error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if(error)
{
NSLog(#"ERROR while loading from file: %#", error);
}
Write to a file works this way:
Use this method:
- (BOOL)writeToFile:(NSString *)path
atomically:(BOOL)useAuxiliaryFile
encoding:(NSStringEncoding)enc
error:(NSError **)error
Example:
[text writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
Mistake:
Can't just write to bundle path. Need to copy it to Documents Directory.
-(void)copyBundleToDocuments
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"Example.txt"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"Example.txt"];
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success)
{
[text writeToFile:documentPlistPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
}
Your question is so broad one could drive a truck (or lorry, in UK English) through the middle of it.
But in general, you could add a UITextView to one of your view controllers.
And when you are ready to save, you could take the contents of the text view (which is a NSString), and save it to a file via the NSString writeToFile methods.
And you can load the text view later on via NSString's "initFromFile" method, as long as you know the path to that file.
Here are other questions that people have asked that may help you out.
You can use UITextView to write text
save the file using
[txtView.text writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
Get the TextFile content using
NSString* content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];
I have my App create a file, compress it into a .zip file, then attach it to an email. But the .zip file contains many directories before the actual file. Starting with the '/' which is a nameless folder and looks invisible to the people receiving it. The top level directory is '/', the next level is 'com'...
/var/mobile/Applications/CDA16BB231BDABABBA/Documents/data.txt
How can I remove all the directories and have the .zip file contain only the file?
Here's the code I have used...
NSError *error;
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory
stringByAppendingPathComponent:#"data.txt"];
NSLog(#"string to write:%#",printString);
[printString writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:&error];
////ZIP FILE/////
NSString *zipfilePath = [documentsDirectory stringByAppendingPathComponent:#"data.zip"];
[[NSFileManager defaultManager] removeItemAtPath: zipfilePath error: &error];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:zipfilePath mode:ZipFileModeCreate];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:zipfilePath error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *stream = [zipFile writeFileInZipWithName:filePath fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:filePath];
[stream writeData:data];
[stream finishedWriting];
[zipFile close];
The problem is that you are saying:
writeFileInZipWithName:filePath
The variable filePath contains that huge long name you are complaining about. It is the whole path from the top all the way down to your actual file.
Your file's name is #"data.txt", so what you want to say is:
writeFileInZipWithName:#"data.txt"
So in my app I have a bunch of data that I'd like to write to a log file, and then display it within a UITextView when I click a button. I know how to toggle the UITextView, but I have no idea how to create and update a log file (in the local filesystem). Thanks for any help.
The basic idea is that you create the file, and append to it every time you log a new line. You can do it quite easily like this:
Writing to the file:
NSString *content = #"This is my log";
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"myFileName.txt"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
Reading:
//get file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"myFileName.txt"];
//read the whole file as a single string
NSString *content = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
I thought was a class out there to do this automatically as after no luck created my own.
NSLogger is a lightweight class for iOS versions 3.0 and above. It allows developers to easily log different 'events' over time which are locally stored as a .txt file.
https://github.com/northernspark/NSLogger