Objective C - How to create rtf from NSAttributedString - ios

I can convert from rtf string to attributed string using following:
NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:#{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
Now how can i convert back from attributedString to rtf string?

You want to use -dataFromRange:documentAttributes:error:
NSAttributedString *str = [[NSAttributedString alloc] initWithString:#"YOLO" attributes:nil];
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:#{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} error:NULL];
[data writeToFile:#"/me.rtf" atomically:YES];
Of course you'd want to have some attributes instead of "YOLO", but you get the idea.
Also, if you're looking to simply write this to disk, then fileWrapperFromRange:documentAttributes:error:
might even be a better option. You can find more about reading and writing from the Attributed String Programming Guide

Related

Objective-C: Equivalent to stringWithFormat for NSMutableAttributedString

I am trying to add a hyperlink in a string. I have a localized string and I put %# to format my string. When I add the attributed string into my string, the attributed format gives the raw result which is NSLink = "https://www.example.com". I could not find an attributed string formatter the same as the string formatter. How can I achieve the same behaviour in my case?
Code:
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:#"Example"];
[str addAttribute: NSLinkAttributeName value: #"https:/www.example.com" range: NSMakeRange(0, str.length)];
NSMutableAttributedString *originalStr = [[NSMutableAttributedString alloc] initWithString: self.pageDescriptions[3].localized];
pageContentViewController.messageText = [NSString stringWithFormat:self.pageDescriptions[index].localized, str];
stringWithFormat: is only doing substitutions of formatters. So if your formatters are simple enough, like a %#, you can just search for it with rangeOfString: and do the substitution yourself with replaceCharactersInRange:withAttributedString:.
NSMutableAttributedString *strWithLink = [[NSMutableAttributedString alloc] initWithString:#"Example"];
[strWithLink addAttribute:NSLinkAttributeName value:#"https:/www.example.com" range:NSMakeRange(0, strWithLink.length)];
NSMutableAttributedString *strWithFormat = [[NSMutableAttributedString alloc] initWithString:#"hello %# world"];
[strWithFormat replaceCharactersInRange:[strWithFormat.string rangeOfString:#"%#"] withAttributedString:strWithLink];
The result here in strWithFormat kept the attributes of strWithLink.
Note: this won't work correctly if your format is complex, like with %%# %# %%#, because it will replace the first occurrence of %#, while stringWithFormat: would have replaced the middle occurrence.
There isn't one. You create the NSAttributedString by hand, or you create an extension that does what you want if you do this a lot.

Remove html tags and display in UILabel Objective c

I am getting &nbsp /br> p> like Html tags in my api response. I want to display those contents in UILabel
What I did is:
NSString *STR_api = [NSString StingWithFormat#:"%#",[API_res valueforkey:#"description"]];
STR_api = [STR_api StringByreplacingaccurancesofString #"&nbsp" with string#""];
What I want is, In web portal it is displaying like bold, paragraph is it possible to display in UILabel by formatting the above response
Thanks in advance
I tried from perfect solution from Larme's answer
I got the solution.It works fine.
NSString *strHTML = #"S.Panchami 01.38<br>Arudra 02.01<br>V.08.54-10.39<br>D.05.02-06.52<br> <font color=red><u>Festival</u></font><br><font color=blue>Shankara Jayanthi<br></font>";
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[strHTML dataUsingEncoding:NSUTF8StringEncoding]
options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:#(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
NSLog(#"html: %#",strHTML);
NSLog(#"attr: %#", attrStr);
NSLog(#"string: %#", [attrStr string]);
NSString *finalString = [attrStr string];
NSLog(#"The finalString is - %#",finalString);
The printed results are
html
html: S.Panchami 01.38<br>Arudra 02.01<br>V.08.54-10.39<br>D.05.02-06.52<br> <font color=red><u>Festival</u></font><br><font color=blue>Shankara Jayanthi<br></font>
string
string: S.Panchami 01.38
Arudra 02.01
V.08.54-10.39
D.05.02-06.52
Festival
Shankara Jayanthi
Final String
The finalString is - S.Panchami 01.38
Arudra 02.01
V.08.54-10.39
D.05.02-06.52
Festival
Shankara Jayanthi
Now for removing &nbsp from string
OPTION 1
NSRange range;
while ((range = [finalString rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
finalString = [finalString stringByReplacingCharactersInRange:range withString:#""];
OPTION 2
finalString = [finalString stringByReplacingOccurrencesOfString:#"&nbsp" withString:#""];
Remove HTML Tags from String
try this code:
NSString *strDescription = [NSString stringWithFormat:#"%#",[API_res valueforkey:#"description"]];
self.lblDescription.attributedText = [self getData:strDescription];
Convert HtmlString to string
-(NSAttributedString *)getData:(NSString *)str
{
NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = #{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
NSAttributedString *decodedString;
decodedString = [[NSAttributedString alloc] initWithData:stringData
options:options
documentAttributes:NULL
error:NULL];
return decodedString;
}
Use below UILabel formatting control which provides Rich text formatting based on HTML-like markups for iOS.
RTLabel

Saving NSAttributedString to Parse.com

Parse doesn't support direct saving of NSAttributedStrings. Converting to HTML isn't the most straightforward. Anyone have a friendly method for storing NSAttributedStrings (font & superscript) to Parse.com?
Thanks guys, decided to go with saving an rtf string onto Parse, based off #Wain's comment.
// convert NSAttributedString to RTFString and save to Parse
PFObject *note = [PFObject objectWithClassName:#"Note"];
NSAttributedString *noteAttributedText = self.noteTextView.attributedText;
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSRTFTextDocumentType,NSDocumentTypeDocumentAttribute, nil];
NSData *rtfData = [noteAttributedText dataFromRange:NSMakeRange(0, noteAttributedText.length) documentAttributes:documentAttributes error:NULL];
NSString *rtfString = [[NSString alloc] initWithData:rtfData encoding:NSUTF8StringEncoding];
note[#"noteTextAsRTFString"] = rtfString;
// convert RTFString to NSAttributedString after pulling from Parse
NSString *rtfString = [pfObject objectForKey:#"noteTextAsRTFString"];
NSData *data = [rtfString dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *noteAttributedText = [[NSAttributedString alloc] initWithData:data options:#{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];

Writing NSAttributedString to Dropbox file iOS

How can I write an attributed string to a Dropbox file? I'm trying to create a header for my file, but I don't know how to change the text format within the Dropbox file.
Something like:
DBPath *newPath = [[DBPath root] childPath:#"hello.txt"];
DBFile *file = [[DBFilesystem sharedFilesystem] createFile:newPath error:nil];
UIFont *font = [UIFont fontWithName:#"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
NSAttributedString *string = [[NSAttributedString alloc] initWithString:#"Title" attributes:attrsDictionary];
if (file)
[file writeString:string error:nil];
NSAttributedString does not have methods to read/write to a file directly. However it does conform to the NSCoding protocol so it's possible to serialize it to a file, with code like this:
[NSkeyedArchiver archiveRootObject: string toFile: myFilePath];
And then to read it back:
NSAttributedString *string =
[NSKeyedUnarchiver unarchiveObjectWithFile: myFilePath];
Note that the file format is not suitable for exchanging styled text with other platforms/applications. If you archive an attributed string using NSkeyedArchiver, the only thing you can do with the resulting file is to unarchive it with NSKeyedUnarchiver;

How to convert formatted content of NSTextView to string

I need transfer content of NSTextView from Mac app to iOS app. I'm using XML as transfered file format.
So I need to save content of NSTextView (text, fonts, colors atd.) as a string. Is there any way how to do that?
One way to do this is to archive the NSAttributedString value. Outline sample code typed directly into answer:
NSTextView *myTextView;
NSString *myFilename;
...
[NSKeyedarchiver archiveRootObject:myTextStorage.textStorage
toFile:myFilename];
To read it back:
myTextView.textStorage.attributedString = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilename];
That's all that is needed to create and read back a file. There are matching methods which create an NSData rather than a file, and you can convert an NSData into an NSString or just insert one into an NSDictionary and serialise that as a plist (XML), etc.
Your best bet is probably to store the text as RFTD and load it as such in the other text view via an NSAttributedString.
// Load
NSFileWrapper* filewrapper = [[NSFileWrapper alloc] initWithPath: path];
NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper: filewrapper];
NSAttributedString* origFile = [NSAttributedString attributedStringWithAttachment: attachment];
// Save
NSData *data = [origFile RTFDFromRange: NSMakeRange(0, [origFile length]) documentAttributes: nil];
[[NSFileManager defaultManager] createFileAtPath: path contents: data attributes:nil];

Resources