Ravi Malviya Ravi Malviya - 5 months ago 48
iOS Question

Html string convert into attributed string with \U00002028\n ios

Html string get it from server I tried convert into attributed string.
using

NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding] }
documentAttributes: nil
error: nil
];


attribute string having \U00002028\n that causes display string got spacing and line breaking in text.How can be able to remove such thing.

Answer

Trim leading and trailing whitespaces from NSMutableAttributedString

NSString * _strAchievementMsg= @"  Hi Test the White space    ";

NSString * htmlString = [NSString stringWithFormat:@"<html><div>%@</div></html>",_strAchievementMsg];

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]
                                        initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                                        options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding] }
                                        documentAttributes: nil
                                        error: nil
                                        ];
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange range           = [attString.string rangeOfCharacterFromSet:charSet];
while (range.length != 0 && range.location == 0)
{
    [attString replaceCharactersInRange:range withString:@""];
    range = [attString.string rangeOfCharacterFromSet:charSet];
}

// Trim trailing whitespace and newlines.
range = [attString.string rangeOfCharacterFromSet:charSet
                                          options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) == attString.length)
{
    [attString replaceCharactersInRange:range
                             withString:@""];
    range = [attString.string rangeOfCharacterFromSet:charSet
                                              options:NSBackwardsSearch];
}