Created
September 25, 2012 09:17
-
-
Save datwelk/3780805 to your computer and use it in GitHub Desktop.
Emoji's, ranges and attributed strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // The issue: the Twitter API returns so called 'tweet entities' for each tweet. These entities contain the ranges | |
| // of hashtags, mentions and urls in the tweet. In iOS, emoji's have a length of 2. The Twitter API uses 1 as length | |
| // for the emoji's. So when you try to change the foreground color attribute in the range Twitter gives, you change | |
| // the foreground color of a part of the emoji. The affected thread will freeze and ultimately crash. | |
| // This code fixes the issue with emoji's, but does not yet work with composed character sequences longer than 2. | |
| // Feel free to fork/comment. | |
| NSRange range; // The old, corrupted range that doesn't take emoji's in account | |
| NSString *string; // The string | |
| __block NSRange adjustedRange = range; | |
| __block NSInteger count = 0; | |
| [string enumerateSubstringsInRange:NSMakeRange(0, string.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) | |
| { | |
| adjustedRange.length += (substring.length > 1) ? 1 : 0; | |
| adjustedRange.location += (substring.length > 1) ? 1 : 0; | |
| count += 1; | |
| if (range.length == count) *stop = YES; | |
| }]; | |
| // Do something with the adjusted range |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment