From 4d6395e5486a4261c9482d4f0855c950c73c482d Mon Sep 17 00:00:00 2001 From: Satoshi Nakagawa Date: Tue, 8 May 2012 12:37:12 -0700 Subject: [PATCH] Add remainingCharacterCount: method. --- lib/TwitterText.h | 3 +++ lib/TwitterText.m | 67 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/lib/TwitterText.h b/lib/TwitterText.h index 85a4a79..774e028 100644 --- a/lib/TwitterText.h +++ b/lib/TwitterText.h @@ -24,4 +24,7 @@ + (int)tweetLength:(NSString*)text; ++ (int)remainingCharacterCount:(NSString*)text; ++ (int)remainingCharacterCount:(NSString*)text httpURLLength:(int)httpURLLength httpsURLLength:(int)httpsURLLength; + @end diff --git a/lib/TwitterText.m b/lib/TwitterText.m index dbb00a6..ae2a410 100644 --- a/lib/TwitterText.m +++ b/lib/TwitterText.m @@ -272,6 +272,10 @@ @")" \ @")" +static const int MaxTweetLength = 140; +static const int HTTPShortURLLength = 14; +static const int HTTPSShortURLLength = 15; + static NSRegularExpression *validURLRegexp; static NSCharacterSet *invalidURLWithoutProtocolPrecedingCharSet; static NSRegularExpression *validASCIIDomainRegexp; @@ -607,6 +611,7 @@ + (int)tweetLength:(NSString*)text return 0; } + // Adjust count for non-BMP characters UniChar buffer[len]; [text getCharacters:buffer]; int charCount = len; @@ -623,8 +628,68 @@ + (int)tweetLength:(NSString*)text } } } - + return charCount; } ++ (int)remainingCharacterCount:(NSString*)text +{ + return [self remainingCharacterCount:text httpURLLength:HTTPShortURLLength httpsURLLength:HTTPSShortURLLength]; +} + ++ (int)remainingCharacterCount:(NSString*)text httpURLLength:(int)httpURLLength httpsURLLength:(int)httpsURLLength +{ + text = [text precomposedStringWithCanonicalMapping]; + + if (!text.length) { + return MaxTweetLength; + } + + // Remove URLs from text and add t.co length + NSMutableString *string = [text mutableCopy]; +#if !__has_feature(objc_arc) + [string autorelease]; +#endif + + int urlLengthOffset = 0; + NSArray *urlEntities = [self extractURLs:text]; + for (int i=urlEntities.count-1; i>=0; i--) { + TwitterTextEntity *entity = [urlEntities objectAtIndex:i]; + NSRange urlRange = entity.range; + NSString *url = [string substringWithRange:urlRange]; + if ([url rangeOfString:@"https" options:NSCaseInsensitiveSearch | NSAnchoredSearch].location == 0) { + urlLengthOffset += httpsURLLength; + } else { + urlLengthOffset += httpURLLength; + } + [string deleteCharactersInRange:urlRange]; + } + + int len = string.length; + int charCount = len; + + if (len > 0) { + // Adjust count for non-BMP characters + UniChar buffer[len]; + [string getCharacters:buffer]; + + for (int i=0; i