Skip to content

Instantly share code, notes, and snippets.

@jbrennan
Created June 19, 2014 20:42
Show Gist options
  • Save jbrennan/fff0fe2200adaa1044fb to your computer and use it in GitHub Desktop.
Save jbrennan/fff0fe2200adaa1044fb to your computer and use it in GitHub Desktop.
Finding emojis in NSStrings
// This is bad and I feel bad. Suggestions for improvements on finding Emoji?
// This current solution is acceptable for us right now, but obviously the less I have to exclude the better.
@interface NSString (Emoji)
/**
Returns if the receiver may contain Emoji characters.
@note This method may have false-positives since it sees if the string has non-ASCII characters. If the receiver has a non-Emoji, non-ASCII character (like é) then it will still return YES.
*/
- (BOOL)maybeContainsEmoji;
@end
@implementation NSString (Emoji)
- (BOOL)maybeContainsEmoji
{
NSData *stringData = [self dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
return ![[[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding] isEqualToString:self];
}
@end
@frozendevil
Copy link

You could do something like

static NSSet *emojiSet = [NSSet setWithObjects:/* all the emoji */];

__block BOOL hasEmoji = NO;
[self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByComposedCharacterSequences block:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    if([emojiSet containsObject:substring]) {
        hasEmoji = YES;
        &stop = YES;
    }
}];

(note this is off the top of my head so may not actually compile)

There are obvious tradeoffs here that may or may not work for your case, though


Whoops, @mattbischoff's answer is similar/better

@jbrennan
Copy link
Author

Thanks 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment