I want to convert an NSAttributedString, to html like this:
This is a string with some simple html<
Here's a more complete solution that preserves more styles and links.
Check out the other keys in NSAttributedString.h if you want to preserve color and kerning information.
@implementation NSAttributedString (SimpleHTML)
- (NSString*) simpleHTML
{
NSMutableAttributedString* attr = [self mutableCopy];
[attr enumerateAttributesInRange: NSMakeRange(0, [self length])
options: 0
usingBlock: ^(NSDictionary * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop)
{
for (NSString* aKey in attrs.allKeys.copy)
{
NSString* format = nil;
if ([aKey compare: NSFontAttributeName] == NSOrderedSame) //UIFont, default Helvetica(Neue) 12
{
UIFont* font = attrs[aKey];
BOOL isBold = UIFontDescriptorTraitBold & [[font fontDescriptor] symbolicTraits];
BOOL isItalic = UIFontDescriptorTraitItalic & [[font fontDescriptor] symbolicTraits];
if (isBold && isItalic)
{
format = @"%@";
}
else if (isBold)
{
format = @"%@";
}
else if (isItalic)
{
format = @"%@";
}
}
else if ([aKey compare: NSStrikethroughStyleAttributeName] == NSOrderedSame) //NSNumber containing integer, default 0: no strikethrough
{
NSNumber* strike = (id) attrs[aKey];
if (strike.boolValue)
{
format = @"";
}
else
{
format = @"";
}
}
else if ([aKey compare: NSUnderlineStyleAttributeName] == NSOrderedSame) //NSNumber containing integer, default 0: no underline
{
if ([attrs.allKeys containsObject: NSLinkAttributeName] == NO)
{
NSNumber* underline = (id) attrs[aKey];
if (underline.boolValue)
{
format = @"%@";
}
}
}
else if ([aKey compare: NSLinkAttributeName] == NSOrderedSame) //NSURL (preferred) or NSString
{
NSObject* value = (id) attrs[aKey];
NSString* absolute = @"";
if ([value isKindOfClass: NSURL.class])
{
NSURL* url = (id) value;
absolute = url.absoluteString;
}
else if ([value isKindOfClass: NSString.class])
{
absolute = (id) value;
}
format = [NSString stringWithFormat: @"%%@", absolute];
}
if (format)
{
NSString* occurence = [[attr attributedSubstringFromRange: range] string];
NSString* replacement = [NSString stringWithFormat: format, occurence];
[attr replaceCharactersInRange: range
withString: replacement];
}
}
}];
NSMutableString* result = [[NSString stringWithFormat: @"%@", attr.string] mutableCopy];
[result replaceOccurrencesOfString: @"\n"
withString: @"
"
options: 0
range: NSMakeRange(0, result.length)];
return result;
}
@end
EDIT: I've added the conditional you need to check to enable/disable underline detection while it's treating a URL.