HTML character decoding in Objective-C / Cocoa Touch

后端 未结 13 2227
我寻月下人不归
我寻月下人不归 2020-11-22 10:24

First of all, I found this: Objective C HTML escape/unescape, but it doesn\'t work for me.

My encoded characters (come from a RSS feed, btw) look like this: &a

13条回答
  •  梦谈多话
    2020-11-22 10:57

    As if you need another solution! This one is pretty simple and quite effective:

    @interface NSString (NSStringCategory)
    - (NSString *) stringByReplacingISO8859Codes;
    @end
    
    
    @implementation NSString (NSStringCategory)
    - (NSString *) stringByReplacingISO8859Codes
    {
        NSString *dataString = self;
        do {
            //*** See if string contains &# prefix
            NSRange range = [dataString rangeOfString: @"&#" options: NSRegularExpressionSearch];
            if (range.location == NSNotFound) {
                break;
            }
            //*** Get the next three charaters after the prefix
            NSString *isoHex = [dataString substringWithRange: NSMakeRange(range.location + 2, 3)];
            //*** Create the full code for replacement
            NSString *isoString = [NSString stringWithFormat: @"&#%@;", isoHex];
            //*** Convert to decimal integer
            unsigned decimal = 0;
            NSScanner *scanner = [NSScanner scannerWithString: [NSString stringWithFormat: @"0%@", isoHex]];
            [scanner scanHexInt: &decimal];
            //*** Use decimal code to get unicode character
            NSString *unicode = [NSString stringWithFormat:@"%C", decimal];
            //*** Replace all occurences of this code in the string
            dataString = [dataString stringByReplacingOccurrencesOfString: isoString withString: unicode];
        } while (TRUE); //*** Loop until we hit the NSNotFound
    
        return dataString;
    }
    @end
    

提交回复
热议问题