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"
Related
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);
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.
I am writing a registration app that is supposed to save a CSV file in the documents directory folder. I would like to look at the output and see what happens when I open the CSV file in excel. I navigated to the documents directory folder by finding out where it should be saved using this code snippet:
NSLog(#"Info Saved");
NSLog(#"Documents Directory: %#", [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject]);
Here is my code for saving the information put into the 11 text fields in the registration form:
- (IBAction)saveFormButton:(id)sender {
// saves text field data in comma separated CSV file format
NSString *formData = [NSString stringWithFormat:#"%#,%#,%#,%#,%#,%#,%#,%#,%#,%#,%#\n",
self.nameTextfield.text, self.emailTextfield.text,
self.phoneTextfield.text, self.termTextfield.text,
self.schoolTextfield.text, self.graduationTextfield.text,
self.gpaTextfield.text, self.degreeTextfield.text,
self.interestTextfield.text, self.groupTextfield.text,
self.appliedTextfield.text];
// get document directory path
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0];
// append results.csv onto doc path
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
// creates folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
Should I be seeing a file in that specific folder I have navigated to?
Thank you for your help,
Change this line:
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
to:
NSString *event = [documentDirectoryPath stringByAppendingPathComponent:#"results.csv"];
This makes sure that the path is correctly formatted. Also, you seem to be checking to see if "documentDirectoryPath" exists before creating the file rather than the filename itself. Change:
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
to:
if (![[NSFileManager defaultManager] fileExistsAtPath:event]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
Here is a more elegant way with less code
// Content of file
NSString* str= #"str,hey,so,good";
// Writing
NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:#"file.csv"];
[str writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
// Reading
NSString *string = [[NSString alloc] initWithContentsOfFile:root encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",string);
The result:
2015-07-15 15:52:56.267 ObjC[2927:15828] str,hey,so,good
i want to create folder in document directory and want to save images in that folder. i have tried but the folder and the images are storing in document directory..But i want to store the images inside the folder.my code is working fine but the images are not saving inside Folder..
NSError *error;
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:#"Folder"];
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSInteger anIndex = 0;
for (UIImage *anImage in _chosenImages)
{
NSString *anImageName = [NSString stringWithFormat:#"%d.png", anIndex++];
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", aDocumentsDirectory, anImageName];
NSLog(#"the path is=%#",anImagePath);
NSData *anImageData = UIImagePNGRepresentation(anImage);
[anImageData writeToFile:anImagePath atomically:YES];
}
I guess your "anImagePath" is still pointing to documents directory.
edit it as "dataPath" as the argument as below
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", dataPath, anImageName];
try this..
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
actually you arr passing NO in "withIntermediateDirectories" parameter, and if you pass NO to this than if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.
So I am using this library: https://github.com/flyingdolphinstudio/Objective-Zip
I implemented it and am trying to take a UIImage and NSString and make it a .png and .txt in the .zip file, respectively.
Now these are my 2 concerns, I am trying to save the *zipFile below to the documents directory.
Now with the dropbox API, how come I can't just provide the file itself and skip the path. It seems like I HAVE to save the .zip to the documents directory first and then get the path so I can then upload it to dropbox. Do I have to do that?
In the ...writeToFile line, I am getting a warning that ZipFile may not respond to writeToFile so how would I properly save it to the documents directory?
Anyway this is the code I have so far:
NSString *filename = [NSString stringWithFormat:#"%#.zip", textField.text];
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:filename mode:ZipFileModeCreate];
//Image
NSString *nameImage = #"Image.png";
NSMutableDictionary *theDictionary = [Singleton sharedSingleton].dictionary;
NSData *data = [theDictionary objectForKey:#"image"];
ZipWriteStream *writeImage = [zipFile writeFileInZipWithName:nameImage compressionLevel:ZipCompressionLevelBest];
[writeImage writeData:data];
[writeImage finishedWriting];
//Text
NSString *nameText = #"Text.txt";
NSData *dataText = [textView.text dataUsingEncoding:NSUTF8StringEncoding];
ZipWriteStream *writeText = [zipFile writeFileInZipWithName:nameText compressionLevel:ZipCompressionLevelBest];
[writeText writeData:dataText];
[writeText finishedWriting];
//Now we HAVE to save it to the documents directory to get it to work with dropbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename]; //Add the file name
[zipFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
//Save to Dropbox
NSString *zipPath = [[NSBundle mainBundle] pathForResource:textField.text ofType:#"zip"];
[[self restClient] uploadFile:filename toPath:#"/" withParentRev:nil fromPath:zipPath];
So what am I doing wrong here?
Thanks!
It looks to me like ZipFile already writes to a file, so there's no need for something like writeToFile. Just initialize zipFile with the path you want, be sure to close the file at the end ([zipFile close]), and then upload to Dropbox as you would any other file.