Skip to content

Instantly share code, notes, and snippets.

@penso
Created September 9, 2013 13:41
Show Gist options
  • Save penso/6495732 to your computer and use it in GitHub Desktop.
Save penso/6495732 to your computer and use it in GitHub Desktop.
Detect remaining chars for a tweet
#define TWEET_MAX_LENGTH 140
#define TWEET_URL_HTTP_LENGTH 22
#define TWEET_URL_HTTPS_LENGTH 23
+ (NSInteger) remainingChars:(NSString *)text {
NSInteger result = TWEET_MAX_LENGTH - [text length];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"https?://(\\S+)"
options:0
error:&error];
NSArray *matches = [regex matchesInString:text
options:0
range:NSMakeRange(0, text.length)];
for (NSTextCheckingResult *match in matches) {
NSRange urlRange = [match rangeAtIndex:1];
NSString* url = [text substringWithRange:urlRange];
result += urlRange.length;
if ([url hasPrefix:@"https"]) {
result -= TWEET_URL_HTTPS_LENGTH;
} else {
result -= TWEET_URL_HTTP_LENGTH;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment