How to display a .rtf file into a UITextView - ios

I've created a T&C for my app in TextMate. Then pasted it to a .rtf file created by XCode.
The content of the file is shown but I can see back-slashes when there are line breaks. What am I missing that this is happening?
NSError *e = Nil;
NSString * tc = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"termsAndConditions" ofType:#"rtf"] encoding:NSUTF8StringEncoding error:&e];
NSLog(#"%#",e);
tvView.text = tc;

.rtf file always contains Tags with itself for formating text color alignment and other properties, Try using a .txt file instead.
In TextEdit> Create a .txt file>Copy the contents from .rtf to .txt and use it.
You can use the same code by just renaming the file type.
NSError *e = Nil;
NSString * tc = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"termsAndConditions" ofType:#"txt"] encoding:NSUTF8StringEncoding error:&e];
NSLog(#"%#",e);
tvView.text = tc;

Couldn't you just replace the backslashes with blank ?
Such as
tc = [tc stringByReplacingOccurrencesOfString:#"\" withString:#""];

Related

NSBundle files with the same name but different Upper / Lower case at first letter

I have been working on a project where I added a file into the app bundle. I didn't relise that the project already included the same name file but with a small difference. The difference is the first letter in name in upper/lower case. I wanted to know how the foundation framework classes load resources in such a case.
Here is a test:
NSString *pathentities = [[NSBundle mainBundle] pathForResource:#"entities" ofType:#"json"];
NSString *pathEntities = [[NSBundle mainBundle] pathForResource:#"Entities" ofType:#"json"];
NSError *error = nil;
NSString *entities = [NSString stringWithContentsOfFile:pathentities encoding:NSUTF8StringEncoding error:&error];
NSString *Entities = [NSString stringWithContentsOfFile:pathEntities encoding:NSUTF8StringEncoding error:&error];
NSLog(#"entities : %# , Entities : %#", entities, Entities);
Entities.json file content: "Entities"
entities.json file content: "entities"
NSLog output:
entities : Entities, Entities : (null)

read/write from a .txt file iOS 7 objc

I have this code:
NSString *studentList = _textIn.text;
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:#"ClassOne.txt"];
[studentList writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#", studentList);
NSLog(#"students 1 saved");
I try to write to a text file on the phone system. When I try to read from that file with:
NSError *error;
NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: #"classOne" ofType: #"txt"] encoding:NSUTF8StringEncoding error:&error];
_textIn.text = strFileContent;
The textfield comes up blank. The NSLog prints what was in the text field but when I try to load it up later the textfield is empty. how do I get the textfield to display what is in the file.
The writing part is alright. You are trying to read the file from your application main bundle instead of your original file path.

iOS: read raw plist

I want to read the UserDefaults plist but not as Dictionary or Data. I want it as string like it is when you open it with an editor.
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *homeDir = [documentsPath stringByReplacingOccurrencesOfString:#"Documents" withString:#""];
NSString *defaultsPath = [homeDir stringByAppendingString:[NSString stringWithFormat:#"Library/Preferences/%#.plist", [[NSBundle mainBundle] bundleIdentifier]]];
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
Already tried:
`NSString *contents = [NSString stringWithContentsOfFile:defaultsPath encoding:NSUTF8StringEncoding error:&error];
which ends up with
The operation couldn’t be completed. (Cocoa error 261.)
Property list formats can be either binary or text. Binary plists can't be loaded into an NSString because strings are for text, not arbitrary binary data. The error you're getting seems to suggest that the file cannot be interpreted as UTF-8, which either means it is encoded using another encoding or is not text at all.
If you are certain that the property list is a text property list, you can use:
NSStringEncoding enc;
NSString *contents = [NSString stringWithContentsOfFile:defaultsPath usedEncoding:&enc error:&error];
This will allow the framework to determine the encoding of the text plist for you. If it isn't a text plist, you can convert it to one using the plutil command line utility:
plutil -convert xml1 file.plist
Or, alternatively you can do this in code by loading the plist using the NSPropertyListSerialization class, obtaining the NSData from it that represents the plist as the XML format, and then convert that to a string.
An example would be [uncompiled and untested]:
// load the file as-is into a data object
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
// convert the plist data into actual property list structure
id plistFile = [NSPropertyListSerialization propertyListWithData:data
options:0
format:NULL
error:&error];
// get the XML representation of the property list
NSData *asXML = [NSPropertyListSerialization dataWithPropertyList:plistFile
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
// convert the NSData object into an NSString object
NSString *asString = [[NSString alloc] initWithData:asXML encoding:NSUTF8StringEncoding];
This should work whether the original plist is in XML or binary format. In this example, I am assuming that the XML representation of the property list is in fact UTF-8 encoded, as this is the most common encoding for XML data.

How to read last n lines in a Text file in Objective C

I have a Text file and it has lot of lines How can i get last 'n' number of lines from the text file? and Can we give Numbers in the text file for each file How can we get it.
You could use NSFileHandle, seekToEndOfFile and then work backwards from the offsetInFile using seekToFileOffset: and readDataOfLength: scanning the data read each time for carriage returns and counting them until you get to the required number. As you go you can build up the text after each scan.
One way is putting \n to separate your different lines in the text file. Then
NSString* path = [[NSBundle mainBundle] pathForResource:#"filename"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* lines = [content componentsSeparatedByString: #"\n"];
Then you can take the last few elements in the array.
Hope this helps..
Try to use this one:
NSString* textFile = [[NSBundle mainBundle]
pathForResource:#"fileName" ofType:#"txt"];
NSString* fileContents = [NSString stringWithContentsOfFile: textFile
encoding: NSUTF8StringEncoding error: nil];
Separate by new line
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
Here you can get your last 100 objects
NSString* oneLineStr;
for (int i = allLinedStrings.count - 100; i < allLinedStrings.count; i++)
{
oneLineStr = [allLinedStrings objectAtIndex: i];
NSLog#("New Line %#", oneLineStr);
}

writing string to txt file in objective c

Pulling my hair out trying to work this out. i want to read and write a list of numbers to a txt file within my project. however [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] doesnt appear to write anything to the file. I can see there is the path string returns a file path so it seems to have found it, but just doesnt appear to write anything to the file.
+(void)WriteProductIdToWishList:(NSNumber*)productId {
for (NSString* s in [self GetProductsFromWishList]) {
if([s isEqualToString:[productId stringValue]]) {
//exists already
return;
}
}
NSString *string = [NSString stringWithFormat:#"%#:",productId]; // your string
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSError *error = nil;
[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error.localizedFailureReason);
// path to your .txt file
// Open output file in append mode:
}
EDIT: path shows as /var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt so does exist. But reading it back with:
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
returns nothing but an empty string.
You're trying to write to a location that is inside your application bundle, which cannot be modified as the bundle is read-only. You need to find a location (in your application's sandbox) that is writeable, and then you'll get the behavior you expect when you call string:WriteToFile:.
Often an application will read a resource from the bundle the first time it's run, copy said file to a suitable location (try the documents folder or temporary folder), and then proceed to modify the file.
So, for example, something along these lines:
// Path for original file in bundle..
NSString *originalPath = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSURL *originalURL = [NSURL URLWithString:originalPath];
// Destination for file that is writeable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory];
NSString *fileNameComponent = [[originalPath pathComponents] lastObject];
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent];
// Copy file to new location
NSError *anError;
[[NSFileManager defaultManager] copyItemAtURL:originalURL
toURL:destinationURL
error:&anError];
// Now you can write to the file....
NSString *string = [NSString stringWithFormat:#"%#:", yourString];
NSError *writeError = nil;
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", writeError.localizedFailureReason);
Moving forward (assuming you want to continue to modify the file over time), you'll need to evaluate if the file already exists in the user's document folder, making sure to only copy the file from the bundle when required (otherwise you'll overwrite your modified file with the original bundle copy every time).
To escape from all the hassle with writing to a file in a specific directory, use the NSUserDefaults class to store/retrieve a key-value pair. That way you'd still have hair when you're 64.

Resources