Writting the contents of an array to a text file - cocoa-touch

I'm trying to take the contents of an array and save that data into a text file and then email that file. The text file shows up on the email screen, but when I actually receive the email, nothing is attached. I'm not getting any errors, but I'm also not sure that my data is actually being written into my text file.
// create text file
NSString *path = [[NSBundle mainBundle] pathForResource:#"EmailSignUpData"
ofType:#"txt"];
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
// write the contents of the array into the text file to send
[personArray writeToFile:data atomically:YES];
// attach the text file
NSData *myData = [NSData dataWithContentsOfFile: path];
[mailer addAttachmentData:myData mimeType:#"text/plain"
fileName:#"EmailSignUpData.txt"];
Thanks for the help in advance!!

Related

Is it possible to read and write to a .h file with objective c?

I'm trying to make an xcode plugin that needs to write something to the .h file from the .m file. I haven't been able to find a stackoverflow post with an answer on how to do this. I've tried this code
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *contents = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
I've also tried using the StringWithContentsOfFile method, however they both return nil. Is it because you can't read an .h file with this code or is it something else I'm missing.
filePath is this and it's a correct filepath, my ftp client can read it atleast file:///Users/myUserName/Documents/code/macOsDev/XcodePlugIns/XcoderPlugin/XcoderPlugin/XcoderPlugin.h
So my question is, how do I read and write to a .h file? Thanks in advance.
EDIT as requested, some more code however this is as far as I've gotten to the read/write part of my plugin.
NSString *filePath = path;
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *contents = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSError *error;
NSString *contents1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
contents is #"" because data is nil
and contents1 is just nil;
error is error
NSError * domain: #"NSCocoaErrorDomain" - code: 260
in the debugger, but I'm not sure I'm using this error thing correctly.
Use "/Users/myUserName/Documents/code/macOsDev/XcodePlugIns/XcoderPlugin/XcoderPlugin/XcoderPlugin.h".
Dont use 'file://' prefix
Following is the code for reading and writing
NSString *path = #"your/path/tp/.h/file";
NSData *data = [NSData dataWithContentsOfFile:path];
//Get the contents of the file into the mutable string
NSMutableString *contents = [[NSMutableString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
//Make changes to your mutable string
[contents appendString:#"abc"];
//Write it back to the file
[contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

Obj C Reading Files, txt file not found

I'm trying to read information from a text file in an Obj. C program and whenever I try to NSLog the output, I'm getting (null). I've made sure that the text files I'm working with are in my Copy Bundle Resources, which is what all of the other answers I've found have suggested. I'm using the following to access the files:
NSString *rightsPath = [[NSBundle mainBundle] pathForResource:#"Sample Maze Rights" ofType:#"txt"];
NSString *rightsContent = [NSString stringWithContentsOfFile:rightsPath encoding:NSUTF8StringEncoding error:NULL];
Can anyone make any suggestions?
That's what error argument is for.
NSError *error = nil;
NSString *rightsContent = [NSString stringWithContentsOfFile:rightsPath
encoding:NSUTF8StringEncoding
error:&error];
if (rightsContent == nil)
NSLog(#"error: %#", [error description]);

How to refresh the HTML file which is in NSDocumentDirectory? (more than one time)

I am using HTML file to generate pdf file in DocumentDirectory. Every time I need to refresh
(with new image which is having same name in html file) HTML file when below method is calling.
Right now i am doing like this, but it is refreshing for only first time(when ever i am calling this method)
-(void)RefreshingHTML
{
// fetching path
NSArray* deletepath_forDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString* deletedocumentsDirectoryfiles = [deletepath_forDirectory objectAtIndex:0];`
// Delete HTML file in DocumentDirectory
NSString *deleteHTMLPath = [deletedocumentsDirectoryfiles stringByAppendingPathComponent:#"HTML_Demo.html"];
NSString *deletePDFPath = [deletedocumentsDirectoryfiles stringByAppendingPathComponent:#"HTML_Demo.pdf"];
NSLog(#"delete HTML file Path : %#",deleteHTMLPath);
if([[NSFileManager defaultManager] fileExistsAtPath:deleteHTMLPath]) {
[[NSFileManager defaultManager] removeItemAtPath:deleteHTMLPath error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:deletePDFPath error:NULL];
}
// fetching HTML file from supporting files
NSString *path = [[NSBundle mainBundle] pathForResource:#"HTML_Demo" ofType:#"html"];
NSURL *pathURL = [NSURL fileURLWithPath:path];
NSArray* path_forDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString* documentsDirectory = [path_forDirectory objectAtIndex:0];
// saving HTML file to DocumentDirectory
NSData* data = [NSData dataWithContentsOfURL:pathURL];
[data writeToFile:[NSString stringWithFormat:#"%#/HTML_Demo.html",documentsDirectory] atomically:YES];
// Fetching HTML file from DocumentDirectory
NSString *HTMLPath = [documentsDirectory stringByAppendingPathComponent:#"HTML_Demo.html"];
NSLog(#"delete HTML file Path: %#",HTMLPath);
if([[NSFileManager defaultManager] fileExistsAtPath:HTMLPath]) {
NSURL *targetURL = [NSURL fileURLWithPath:HTMLPath];
// Converting HTML to PDF
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:targetURL
pathForPDF:[#"~/Documents/HTML_Demo.pdf" stringByExpandingTildeInPath]
delegate:self
pageSize:kPaperSizeA4
margins:UIEdgeInsetsMake(20, 5, 90, 5)];
}
}
The URL may be loading from cache. In NDHTMLtoPDF.m, look in viewDidLoad:
Instead of: [webview loadRequest:[NSURLRequest requestWithURL:self.URL]];
Try using the constructor that allows you to set cachePolicy:
NSURLRequest requestWithURL:<#(NSURL *)#> cachePolicy:<#(NSURLRequestCachePolicy)#> timeoutInterval:<#(NSTimeInterval)#>
This policy might work better for your needs: NSURLRequestReloadIgnoringCacheData
Or you could just add something to your URL's querystring so it's never found in cache (e.g., an index or timestamp).

read local html file and show on webview

I have been able to read a file called 'exerciseA.htm' from a live url. but now i need to bring the file locally add it to the project and read it from there. I have dragged the file into xcode to add it. Now i need to read its contents to a string, however the following doesnt seem to work:
NSString* exerciseAPage = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"exerciseA" ofType:#"htm"] encoding:NSUTF8StringEncoding error:&error];
[exerciseWebViewA loadHTMLString:exerciseAPage baseURL:nil];
Is this the correct way to load local htm file to a webview?
I do it the following way (Which is basically the same as you specify):
NSURL *url = [[NSBundle mainBundle] URLForResource:nameOfHtmlFile withExtension:#"html"];
NSError *error;
NSString *contentString = [NSString stringWithContentsOfURL:url encoding:NSStringEncodingConversionAllowLossy error:&error];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:contentString baseURL:baseUrl];
Hope this helps
Alex

Crash on writeToFile

I'm using quite a simple method of storing file names in a text file. For some reason when I initiate the writeToFile I get a crash:
pathString = [NSString stringWithFormat:#"New FileName - %#.png", identifier];
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
NSString *newContents = [NSString stringWithFormat:#"%#:::%#",currentContents, pathString];
NSData *newData = [newContents dataUsingEncoding:NSUTF8StringEncoding];
[newData writeToFile:saveFilePath options:NSDataWritingAtomic error:nil];
It reads the file, places it's contents into a variable called currentContents, then adds the new string to the file, and re-writes it. What's going wrong here.
Without the writeToFile line it works, with it, I get a crash.
Origin of saveFilePath
NSString *saveDocument = [NSString stringWithFormat:#"SavedFile.txt"];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
saveFilePath = [docsDirectory stringByAppendingPathComponent:saveDocument];
An NSLog of saveFilePath reveals a correct path
I think your problem might actually be a missing null character ('\0') at the end of your NSData object. So you finally end up with messed up data. You might want to use -writeToFile:atomically:encoding:error: on your new string right away anyway.
It turns out that the reason the file wasn't writing was because of an unallocated variable:
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
should have been:
NSString *currentContents = [[NSString alloc] initWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];