0

I have an NSString and would like to check if a given character at a certain index is an emoji.

However, there doesn't seem to be any reliable way to create an NSCharacterSet of emoji characters, since they change from iOS update to update. And a lot of the available solutions rely on Swift features such as UnicodeScalar. All solutions seem to involve hardcoding the codepoint values for emojis.

As such, is it possible to check for emojis at all?

jscs
  • 63,694
  • 13
  • 151
  • 195
Apophenia Overload
  • 2,485
  • 3
  • 28
  • 46
  • 1
    There's is no provided API that checks just for Emoji. I haven't tried it but see https://stackoverflow.com/a/14472163/1226963 which uses an interesting solution to detecting an Emoji. It seems to treat any non-all black character as an Emoji. – rmaddy Jan 16 '19 at 22:10
  • I think this helper function should help you: https://gist.github.com/cihancimen/4146056. – Mo Abdul-Hameed Jan 16 '19 at 22:26
  • The function in the gist doesn't seem to cover all emojis, sadly. – Apophenia Overload Jan 17 '19 at 23:25

1 Answers1

3

It's a bit of a complicated question because Unicode is complicated, but you can use NSRegularExpression to do this:

    NSString *s = @"where's the emoji  ?";
    NSRegularExpression *r = [NSRegularExpression regularExpressionWithPattern:@"\\p{Emoji_Presentation}" options:0 error:NULL];
    NSRange range = [r rangeOfFirstMatchInString:s options:0 range:NSMakeRange(0, s.length)];
    NSLog(@"location %lu length %lu", (unsigned long)range.location, (unsigned long)range.length);

produces:

2019-01-16 18:07:42.629 emoji[50405:6837084] location 18 length 2

I'm using the \p{Unicode property name} pattern to match characters which have the specified Unicode property. I'm using the property Emoji_Presentation to get those character which present as Emoji by default. You should review Unicode® Technical Standard #51 — Annex A: Emoji Properties and Data Files and the data files linked in A.1 to decide which property you actually care about.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • 3
    See https://stackoverflow.com/a/39122453/1226963 which seems to indicate that it's far more complex than just using `Emoji_Presentation`. – rmaddy Jan 17 '19 at 00:53