NSString+Emoji.m 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2016-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "NSString+Emoji.h"
  21. #import <CoreText/CoreText.h>
  22. static CFMutableCharacterSetRef *emojiCharacterSet = nil;
  23. @implementation NSString (Emoji)
  24. + (void)load {
  25. static CFMutableCharacterSetRef set = nil;
  26. static dispatch_once_t onceToken;
  27. dispatch_once(&onceToken, ^{
  28. set = CFCharacterSetCreateMutableCopy(kCFAllocatorDefault, CTFontCopyCharacterSet(CTFontCreateWithName(CFSTR("AppleColorEmoji"), 0.0, NULL)));
  29. CFCharacterSetRemoveCharactersInString(set, CFSTR(" 0123456789#*"));
  30. });
  31. emojiCharacterSet = &set;
  32. }
  33. - (BOOL)isOnlyEmojisMaxCount:(int)maxCount {
  34. NSString *withoutWhiteSpaceString = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
  35. NSAttributedString *richText = [[NSAttributedString alloc] initWithString:withoutWhiteSpaceString];
  36. CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)richText);
  37. CFIndex glyphCount = CTLineGetGlyphCount(line);
  38. CFRelease(line);
  39. if (glyphCount > 0 && glyphCount <= maxCount) {
  40. BOOL __block result = YES;
  41. [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
  42. if (![substring containsEmoji]) {
  43. if (![substring isWhiteSpace]) {
  44. *stop = YES;
  45. result = NO;
  46. }
  47. }
  48. }];
  49. return result;
  50. }
  51. return NO;
  52. }
  53. - (BOOL)containsEmoji {
  54. return CFStringFindCharacterFromSet((CFStringRef)self, *emojiCharacterSet, CFRangeMake(0, self.length), 0, NULL);
  55. }
  56. - (BOOL)isWhiteSpace {
  57. NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
  58. if ([[self stringByTrimmingCharactersInSet: set] length] == 0) {
  59. return YES;
  60. }
  61. return NO;
  62. }
  63. @end