Created
September 9, 2013 13:41
-
-
Save penso/6495732 to your computer and use it in GitHub Desktop.
Detect remaining chars for a tweet
This file contains 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
#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