Emoji是我们常见的在文字中插入的图形符号,在iOS中可以实现程序自动实现的方式实现此功能;即可在需要展示的文字中添加Emoji表情或者在应用通知中添加。
按照现在理解,其实Emoij也就是一种编码而已。使用一般会按照苹果的使用规则和编码方式进行相应的Emoij对应。
实现代码(.h/.m)如下:
NSString+Emoji.m实现代码:
#import "NSString+Emoji.h"
@implementation NSString (Emoji)
static NSDictionary * s_unicodeToCheatCodes = nil;
static NSDictionary * s_cheatCodesToUnicode = nil;
+ (void)initializeEmojiCheatCodes
{
// 下面的NSDictionary展示的部分Emoji代码
// 详细Emoji代码可见,已封装完成的自定义表情NSString扩展类中
NSDictionary *forwardMap = @{
@"😄": @":smile:",
@"😆": @[@":laughing:", @":D"],
@"😊": @":blush:",
@"😃": @[@":smiley:", @":)", @":-)"],
@"☺": @":relaxed:",
@"😏": @":smirk:",
@"😞": @[@":disappointed:", @":("],
@"😍": @":heart_eyes:"
};
NSMutableDictionary *reversedMap = [NSMutableDictionary dictionaryWithCapacity:[forwardMap count]];
[forwardMap enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
for (NSString *object in obj) {
[reversedMap setObject:key forKey:object];
}
} else {
[reversedMap setObject:key forKey:obj];
}
}];
@synchronized(self) {
s_unicodeToCheatCodes = forwardMap;
s_cheatCodesToUnicode = [reversedMap copy];
}
}
/* 方法使用示例:对照Emoji表情代码
* Example:
* "This is a smiley face :smiley:"
* Will be replaced with:
* "This is a smiley face \U0001F604"
*/
- (NSString *)stringByReplacingEmojiCheatCodesWithUnicode
{
if (!s_cheatCodesToUnicode) {
[NSString initializeEmojiCheatCodes];
}
if ([self rangeOfString:@":"].location != NSNotFound) {
__block NSMutableString *newText = [NSMutableString stringWithString:self];
[s_cheatCodesToUnicode enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
[newText replaceOccurrencesOfString:key withString:obj options:NSLiteralSearch range:NSMakeRange(0, newText.length)];
}];
return newText;
}
return self;
}
/* Example:
"This is a smiley face \U0001F604"
Will be replaced with:
"This is a smiley face :smiley:"
*/
- (NSString *)stringByReplacingEmojiUnicodeWithCheatCodes
{
if (!s_cheatCodesToUnicode) {
[NSString initializeEmojiCheatCodes];
}
if (self.length) {
__block NSMutableString *newText = [NSMutableString stringWithString:self];
[s_unicodeToCheatCodes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *string = ([obj isKindOfClass:[NSArray class]] ? [obj firstObject] : obj);
[newText replaceOccurrencesOfString:key withString:string options:NSLiteralSearch range:NSMakeRange(0, newText.length)];
}];
return newText;
}
return self;
}
@end
NSString+Emoji.h实现调用代码:
Example:
// 加入Emoji表情
NSString *smileEmojiStr = @":blush:"; // 写出此代码对照表情
NSString *str = @"后接表情";
NSString *emojiStr = [str stringByReplacingEmojiCheatCodesWithUnicode];