I am trying to parse a tweet that may contain a url. I want to format the url with a different color/font within the rest of the tweet. So obviously, the url can be placed anywhere in the text. So I have a category method that looks like this :
NSString *urlString = @"";
NSRange startRange = [self rangeOfString:@"http://" options:NSCaseInsensitiveSearch];
if (startRange.length) {
NSString *subStr = [self substringFromIndex:startRange.location];
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange endRange = [subStr rangeOfCharacterFromSet:set];
if (endRange.length) {
NSRange finalRange;
finalRange.location = startRange.location;
finalRange.length = endRange.location - 1;
NSString *finalString = [self substringWithRange:finalRange];
debugTrace(@"finalString : %@", finalString);
}
}
return urlString;
So basically I find the range of http:// in the text and then make a substring from there to the end. From that I look for the first whitespaceAndNewlineCharacterSet and use that as the end of url to find the finalString. However, the line
NSRange endRange = [subStr rangeOfCharacterFromSet:set];
returns garbage value, which makes me think that I am not using the correct NSCharacterSet to find the endRange
Printing description of endRange:
(NSRange) endRange = location=2147483647, length=0
How can I go about this so that I find where the URL has ended.
As mentioned in my comment, it’s not a garbage range value, it’s a representation for
NSNotFound. This means there isn’t any occurrence of whitespace or newlines in the string you have passed it (which is a valid case). As such, we need to prepare for that.Based on your code, I have changed it to check for
NSNotFound. Also, there was no need to subtract 1 from the finalRange length. When I tested this code sample, that cropped the last character from my URL string. Comments have been added to the end of changed/queried lines.I have tested this briefly, and it seems to work.