iphone parse RTF file format programmatically - iphone

I want to edit a text file (basically a rich text editing) like making some text bold, changing font, color etc. I have found many rich text editor programs. But i need to parse a .rtf file and and show the contents, make it possible to edit and save it back to the .rtf file.
So I am not getting any idea to read and write into a .rtf file.

I got a library for RTF Reader and RTF Writer.
https://github.com/omnigroup/OmniGroup/tree/iOS-4.x
Initially you may get many errors on building the library.

Hey I think you can add your .rtf file to a UITextView and once in the UITextView you can make some text bold, changing font, color etc.
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
myTextView.text = myText;
OR
NSError *err = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&err];
if (fileContents == nil) {
NSLog("Error reading %#: %#", filePath, err);
} else {
myTextView.text = fileContents;
}
Also please check the following link
Read/Write RTF File
Refer the answer from Load rtf or text file into UITextView iphone sdk

Related

NSString stringWithContentsOfFile:fileName non-english letters

I have a file with many lines separated by "\n". One of the lines is:
Christian Grundekjøn
I can't read the file unless I delete the line. I use the following code to read line by line:
for (NSString *line in [[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"])
If I don't delete the line, the code wouldn't even go into the for loop at all. Nothing was read. How to handle the non-English letters?
If you are generating the text file from within iOS then you need to make sure you are encoding it with NSUTF8StringEncoding. But given the problem you are reporting, I suspect that you may be pulling in data from another source and that source hasn't encoded the text as UTF8. If this is the case, you may be able to fix the problem outside your app but converting the source file to UTF8.
If you don't know what encoding is used, e.g. because the user has supplied the file, iOS can try to guess it for you. A pattern that I have used successfully is to first try to get the string using UTF8 encoding, for example using the same approach you use. Assuming you write a method, to which you pass a filename, to get the string something like the following:
- (NSString*) stringFromFile: (NSString*) filePath;
{
NSError* error = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: fileName
encoding: NSUTF8StringEncoding
error: &error];
if (stringFromFile) return stringFromFile; // success
NSLog(#"String is not UTF8 encoded. Error: %#", [error localizedDescription]);
NSStringEncoding encoding = 0;
NSError* usedEncodingError = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: path
usedEncoding: &encoding
error: &usedEncodingError];
if (stringFromFile)
{
NSLog(#"Retrieved string using an alternative encoding. Encoding was: %d", encoding);
return stringFromFile;
}
// either handle error or attempt further explicit unencodings here
return nil;
}
In many cases, usedEncoding works very well. But there are edge cases where trying to figure out an encoding can be very tricky. It all depends on the source file.
I had problem with Japanese characters. My solution was when saving file to doc directory
NSString *fileData = [NSString stringWithFormat:#"%#", noteContent];
BOOL isWriteToFile = [fileData writeToFile:notePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
When reading file content
[[NSString alloc] initWithContentsOfFile:fullNotePath usedEncoding:nil error:nil];
In the file, store your data in unicode format or you can also store special character in unicode format.

How to read .rtf File from URL in iPhone App

My app needs to read .rtf file from URL. I am going to read it as
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#.rtf",_URL]];
NSError* error;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
Now when I load this text in UITextView. It gives me tags with { and / characters with the original file text. Please guide me that how can i read the right text which did not include any brackets and html data.
.rtf file always contains Tags with itself for formating text color alignment and other properties..
please open that .rtf file in to text edit and convert all text part of that file to simple text.
then your existing code will work.
else instead of taking the UItextView open it in UIWebview.
hope it will be helpfull for you.
You can use RTF in a UITextView by first transforming it into an NSAttributedString and then setting the value of the UITextView's attributedString property to the NSAttributedString.
NSAttributedString *stringWithRTF = [[NSAttributedString alloc] initWithFileURL:rtfDoc options:#{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} documentAttributes:nil error:nil];
// Instantiate UITextView object
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,self.view.frame.size.width,self.view.frame.size.height)];
textView.attributedText=stringWithRTF;
[self.view addSubview:textView];

How can you create a .xml file and set its contents to equal the contents of an NSString

I am attempting to create a .xml file and set the contents of the file to equal a predetermined string.
I have built the XML and am currently storing it in an NSString.
I want to put the contents of this string into a file with the extension of .xml and send an email with the file as an attachment.
I am able to email PDFs and assumed creating the file with an extension of .xml would be the easy bit, but alas I cannot do it.
If anyone could offer a helping hand I would be much appreciative.
Try something like this:
NSString *path = ...;
NSString *string = ...;
NSError *error;
BOOL ok = [string writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error];
if (!ok) {
// an error occurred
NSLog(#"Error writing file at %#\n%#",path, [error localizedFailureReason]);
// implementation continues ..
Writing to Files and URLs

iPhone - file properties

i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);

Change Download File Name in Cocoahttpserver

I'm using cocoahttpserver in an iphone app, but when I try to download it (by clicking a link in the standard demo app), my sqlite file (myDatabase.sqlite) arrives on my Mac Desktop as "Unknown" with no suffix at all. However, when I "Save As..." it provides the name fine. I would prefer it to save the file with the sqlite suffix.
So, it must be the suffix causing the problems????
If this is the problem, I cannot seem to find a way in the classes to download the correct file name BUT then change it when presenting it to the browser (with a suffix like .backup, or .db, or something that works).
Anyone know where in the classes to change the download file name so the browser (Safari) will not call it "unknown"? Thanks.
The proper way to do this is to use the httpHeaders override in your async file class:
- (NSDictionary *)httpHeaders
{
NSString *key = #"Content-Disposition";
NSString *value = [NSString stringWithFormat:#"attachment; filename=\"%#\"", [filePath lastPathComponent]];
return [NSDictionary dictionaryWithObjectsAndKeys:value, key, nil];
}
I found someone else's code (MyAppSales) and in replyToHTTPRequest, I added the Content-Disposition header as below (in one section of the method), and now it works!
if(!isRangeRequest)
{
// Status Code 200 - OK
response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);
NSString *contentLengthStr = [NSString stringWithFormat:#"%qu", contentLength];
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (CFStringRef)contentLengthStr);
// ************* added this from MyAppSales
if ([httpResponse isKindOfClass:[HTTPFileResponse class]])
{
NSString *baseName = [(NSString *)[(HTTPFileResponse *)httpResponse filePath] lastPathComponent];
NSString *contentDispoStr = [NSString stringWithFormat:#"Content-Disposition: attachment; filename=\"%#\"", baseName];
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Disposition"), (CFStringRef)contentDispoStr);
}
}
I had a same problem and solved it by changing client side code. At the client side I add download attribute to tags.
Download
For Example:
Download