forked from TorutheRedFox/iOS-Discord-Classic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSString+Emojize.m
executable file
·75 lines (62 loc) · 2.7 KB
/
NSString+Emojize.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// NSString+Emojize.m
// Field Recorder
//
// Created by Jonathan Beilin on 11/5/12.
// Copyright (c) 2014 DIY. All rights reserved.
//
#import "NSString+Emojize.h"
@implementation NSString (Emojize)
- (NSString *)emojizedString
{
return [NSString emojizedStringWithString:self];
}
+ (NSString *)emojizedStringWithString:(NSString *)text
{
static dispatch_once_t onceToken;
static NSRegularExpression *regex = nil;
dispatch_once(&onceToken, ^{
regex = [[NSRegularExpression alloc] initWithPattern:@"(:[a-z0-9-+_]+:)" options:NSRegularExpressionCaseInsensitive error:NULL];
});
__block NSString *resultText = text;
NSRange matchingRange = NSMakeRange(0, [resultText length]);
[regex enumerateMatchesInString:resultText options:NSMatchingReportCompletion range:matchingRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
if (result && ([result resultType] == NSTextCheckingTypeRegularExpression) && !(flags & NSMatchingInternalError)) {
NSRange range = result.range;
if (range.location != NSNotFound) {
NSString *code = [text substringWithRange:range];
Boolean found = false;
NSString *unicode = nil;
// search through JSON for emoji
for (NSString* type in self.emojiAliases){
for(NSDictionary* emojiObject in [self.emojiAliases objectForKey:type]) {
for(NSString* name in [emojiObject objectForKey:@"names"]) {
if ([[NSString stringWithFormat:@":%@:", name] isEqualToString:code]) {
found = true;
unicode = [emojiObject objectForKey:@"surrogates"];
break;
}
}
if (found) break;
}
if (found) break;
}
if (found) {
resultText = [resultText stringByReplacingOccurrencesOfString:code withString:unicode];
}
}
}
}];
return resultText;
}
+ (NSDictionary *)emojiAliases {
static NSDictionary *_emojiAliases;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *path = [[NSBundle mainBundle] pathForResource:@"emoji" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
_emojiAliases = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
});
return _emojiAliases;
}
@end